注解:
@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中使用注解(@Cherry)并进行反射操作。通过注解实体类Water的字段,然后在测试类中获取注解信息,演示了注解的获取与字段访问。内容涉及注解的定义、应用以及反射在获取注解和字段值时的使用方法。
4503

被折叠的 条评论
为什么被折叠?



