这是我的注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface TestAnnotation {
String value() default "";
}
这是我的代码。
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder()
.addUrls(ClasspathHelper.forPackage("com.wuxianggujun"))
.addScanners(Scanners.FieldsAnnotated);
//扫描包名
Reflections reflections = new Reflections(configurationBuilder);
TypeRepository typeRepository = new TypeRepository(reflections);
for (Field field : typeRepository.getTypeProperties()) {
TestAnnotation testAnnotation = field.getAnnotation(TestAnnotation.class);
System.out.println("自定义注解:" + testAnnotation.value());
}
这是TypeRepository类
public Set<Field> getTypeProperties() {
if (typeProperties == null) {
typeProperties = reflections.getFieldsAnnotatedWith(TestAnnotation.class);
}
return typeProperties;
}
这是测试类,运行然后就OK了。你就可以获取到自定义注解的内容了,
import com.wuxianggujun.robotcore.annotation.TestAnnotation;
public class Test {
@TestAnnotation("无相孤君")
private String name;
@TestAnnotation()
private int i = 0;
}
原因就是你在百度到的教程告诉你获取字段的代码都是
Set<Field> cao = reflections.getFieldsAnnotatedWith(TestAnnotation.class)
这段话是没有错误的,但是™的没有告诉你需要配置扫描器。
.addScanners(Scanners.FieldsAnnotated);
所以你如果不加扫描器无论如何扫描的都是[]
,
如果你把注解上的@Target(ElementType.FIELD)
改成@Target(ElementType.TYPE)
是可以不需要配置就可以扫描出来的。
百度教程有毒,需要自己看看官方文档吧
给勇士链接Reflections Api