Reflections.getFieldsAnnotatedWith获取不到标记注解的字段

这是我的注解


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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值