我是靠谱客的博主 热心紫菜,这篇文章主要介绍java 反射获取指定注解修饰的field信息,现在分享给大家,希望可以做个参考。

注解:

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Cherry {

    String value() default "default";

}

实体类:

@Data
public class Water {


    private String name;

    @Cherry
    private Double price;

    @Cherry(value = "test")
    private String tag;


}

测试:

public class GetAnno {
    public static void main(String[] args) throws IllegalAccessException {
        Water water = new Water();
        water.setPrice(100D);
        water.setTag("促销");

        //Class<?> clz = Water.class;
        Class<?> clz = water.getClass();
        Field[] declaredFields = clz.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            Cherry annotation = declaredField.getAnnotation(Cherry.class);
            if(annotation != null){
                System.out.println(annotation);
                declaredField.setAccessible(true);
                if(declaredField.getType() == Double.class){
                    System.out.println(true);
                }
                System.out.println(declaredField.getType());
                Object o = declaredField.get(water);
                System.out.println(o.getClass());
                System.out.println(o);
                System.out.println("------------------------------");
            }
        }
    }
}

输出:

@com.luo.project0109.test0908.Cherry(value=default)
true
class java.lang.Double
class java.lang.Double
100.0
------------------------------
@com.luo.project0109.test0908.Cherry(value=test)
class java.lang.String
class java.lang.String
促销
------------------------------

Process finished with exit code 0

最后

以上就是热心紫菜最近收集整理的关于java 反射获取指定注解修饰的field信息的全部内容,更多相关java内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(46)

评论列表共有 0 条评论

立即
投稿
返回
顶部