【发布时间】:2017-12-05 21:30:47
【问题描述】:
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/AnnotationClass 一样
Class<?> Demo = Class.forName("com.this.class.DemoClass")
如何获取方法上的注释。我认为下面的行在这种情况下不起作用
Demo annotation = m.getAnnotation(Demo.class);
【问题讨论】:
-
您能更具体地说明您要完成的工作吗?尝试创建一个minimal, complete and verifiable example。
-
@fragmentedreality 更新了问题,如果您还需要一些信息,请告诉我。
-
我建议您调整问题的标题:术语“注释处理器”在 Java 语言范围内具有 specific meaning。更适合您的目标的术语是 运行时注释扫描 或简称为 introspection。
-
@user1643723 更新了标题。
-
我没有调查您的问题的具体细节,但您是否尝试过使用现有库之一来完成您的任务? fast-classpath-scanner 或其中的一种替代方案会让您的工作更轻松。
标签: java class methods reflection annotation-processing