通过反射将属性注解的默认值赋值给属性:
/*** 通过反射操作注解*/
public class AnnotationAndProxy {@Testpublic void test(){User user = new User("", "", "");System.out.println(user);System.out.println("===============");AnnotationAndProxy.annotationToField(user);System.out.println(user);}/*** 通过反射将属性的注解默认值赋值给属性* @param obj*/private static void annotationToField(Object obj){Class<?> objClass = obj.getClass();//反射获取对象的所有属性Field[] fields = objClass.getDeclaredFields();for (Field field : fields) {//判断属性上是否有相应的注解if (field.isAnnotationPresent(MyAnnotation.class)){//获取注解MyAnnotation fieldAnnotation = field.getAnnotation(MyAnnotation.class);if (fieldAnnotation != null){//获取属性名String fieldName = field.getName();try {//反射获取对象的setter方法,用来设置属性Method fieldSetMethod = objClass.getDeclaredMethod("set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1), String.class);//获取注解默认值String value = fieldAnnotation.value();//将注解默认值赋给对应的属性fieldSetMethod.invoke(obj, value);} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {e.printStackTrace();}}}}}
}
/*** 自定义注解:用在字段上、运行时、将该注解加到javadoc中、允许子类继承父类*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@interface MyAnnotation{String value() default "设初值";
}
/** * 实体类 */
@Data
@ToString
class User{@MyAnnotationprivate String fieldA;private String fieldB;private String fieldC;public User() { }public User(String fieldA, String fieldB, String fieldC) {this.fieldA = fieldA;this.fieldB = fieldB;this.fieldC = fieldC;}
}
日常学习记录!!!