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();
}
}
我的目标是检查几个方法的注释,如果注释中存在注释,我需要获取注释。
Demo annotation = m.getAnnotation(Demo.class);
在上面的示例中,注释在同一文件中声明。如果注释位于不同的包中,我可以执行类似
的操作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 / AnnotationClassClass<?> Demo = Class.forName("com.this.class.DemoClass")
如何获取方法的注释。我认为以下行在这种情况下不起作用
Demo annotation = m.getAnnotation(Demo.class);
答案 0 :(得分:1)
这种方法对我有用。希望这有助于某人。
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);
}
}
}
答案 1 :(得分:0)
当注释动态加载到变量Demo
中时,然后使用该变量获取注释:
Class<?> Demo = Class.forName("com.this.class.DemoClass");
Demo annotation = m.getAnnotation(Demo);