动态类加载时运行时注释扫描 [英] run time annotation scanning when Dynamic class loading
本文介绍了动态类加载时运行时注释扫描的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;
// declare a new annotation
@Retention(RetentionPolicy.RUNTIME)
@interface Demo {
String str();
int val();
}
public class PackageDemo {
// set values for the annotation
@Demo(str = "Demo Annotation", val = 100)
// a method to call in the main
public static void example() {
PackageDemo ob = new PackageDemo();
try {
Class c = ob.getClass();
// get the method example
Method m = c.getMethod("example");
// get the annotation for class Demo
Demo annotation = m.getAnnotation(Demo.class);
// print the annotation
System.out.println(annotation.str() + " " + annotation.val());
} catch (NoSuchMethodException exc) {
exc.printStackTrace();
}
}
public static void main(String args[]) {
example();
}
}
我的目标是检查几种方法的注释和如果注释中存在,我需要获取注释。
My objective is to check the annotation on few methods and if it exists on the annotation , I need to get the annotation.
Demo annotation = m.getAnnotation(Demo.class);
在上面的示例中,注释在同一文件中声明。如果注释在不同的包中,我可以做类似的事情
In the above example , the annotation is declared in the same file. If annotation is in a different package I can do something like
import com.this.class.DemoClass
try {
Class c = ob.getClass();
// get the method example
Method m = c.getMethod("example");
// get the annotation for class Demo
Demo annotation = m.getAnnotation(Demo.class);
但如果我想动态加载DemoClass / AnnotationClass,如
But if I want to load the DemoClass/AnnotationClass dynamically like
Class<?> Demo = Class.forName("com.this.class.DemoClass")
我如何获得关于方法的注释。我认为以下行在这种情况下不起作用
How do I get the annotation on the methods. I think the below line doesn't works in this case
Demo annotation = m.getAnnotation(Demo.class);
推荐答案
这种方法对我有用。希望这有助于某人。
This approach worked for me. hope this helps someone.
DemoClass= (Class<Annotation>) Class.forName("com.this.class.DemoClass");
if (method.isAnnotationPresent(DemoClass)) {
for (Annotation annotation : method.getAnnotations()) {
Class<? extends Annotation> annotationType = annotation.annotationType();
if (annotationType.getName() == "com.this.class.DemoClass") {
for (Method annotationMethod : annotationType.getDeclaredMethods()) {
value= annotationMethod.invoke(annotation, (Object[]) null);
}
}
}
这篇关于动态类加载时运行时注释扫描的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文