我有自己的自定义注解,我想在运行时扫描所有类以查找此注解。做这件事最好的方法是什么?我没有使用Spring。
发布于 2013-01-10 10:03:32
您可以先使用Reflections Library确定类名,然后使用getAnnotations检查注释:
Reflections reflections = new Reflections("org.package.foo");
Set<Class<? extends Object>> allClasses =
reflections.getSubTypesOf(Object.class);
for (Class clazz : allClasses) {
Annotation[] annotations = clazz.getAnnotations();
for (Annotation annotation : annotations) {
if (annotation instanceof MyAnnotation) {
MyAnnotation myAnnotation = (MyAnnotation) annotation;
System.out.println("value: " + myAnnotation.value());
}
}
} 发布于 2013-01-10 10:03:55
您可以使用getClass().getAnnotations()从类中获取注释,或者如果您不想遍历前一个注释的结果,则可以请求一个特定的注释。为了让注解出现在结果上,它的保留必须是运行时的。例如(不是严格正确的):
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface MyAnnotation {}检查Javadoc:Class#getAnnotation(Class)
在此之后,您的类应该像这样进行注释:
@MyAnnotation public class MyClass {} https://stackoverflow.com/questions/14249509
复制相似问题