[英]How to scan classes for custom Annotations?
I have my custom annotation and I want to scan all the classes for this annotation at runtime. 我有我的自定义批注,我想在运行时扫描此批注的所有类。 What is the best way to do this?
做这个的最好方式是什么? I'm not using Spring.
我没有使用Spring。
You could use the Reflections Library to determine the class names first and then use getAnnotations
to check for the annotation: 您可以使用Reflections库来首先确定类名称,然后使用
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());
}
}
}
You might get annotations from the class using getClass().getAnnotations()
or ask for a particular annotation if you don't want to loop over the results of the previous. 您可以使用
getClass().getAnnotations()
从类中获取批注,或者如果您不想遍历前一个的结果,则要求提供特定的批注。 In order for the annotation to appear on the result it's retention must be RUNTIME. 为了使注释出现在结果中,其保留时间必须为RUNTIME。 For example (not strictly correct):
例如(不完全正确):
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface MyAnnotation {}
Check the Javadoc: Class#getAnnotation(Class) 检查Javadoc: Class#getAnnotation(Class)
And after that your class should be annotated like this: 之后,您的班级应该这样注释:
@MyAnnotation public class MyClass {}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.