spring中ReflectionUtils 方法的一些使用
ReflectionUtils.doWithFields 通过反射对对象中属性进行操作
代码举例:
@Component
@Data
@ToString
public class Cart implements InitializingBean {
public Cart() {
System.out.println("构造器");
}
@FieldMapping("ID")
private Integer id;
@FieldMapping("DESC-lq")
private String desc;
@PostConstruct
public void init() {
System.out.println("init");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("initializingBean");
}
}
@Target({ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface FieldMapping {
String value() default "";
String description() default "";
}
@Test
public void testReflectionUtil() {
Map<String, Object> map = new HashMap<>(2);
map.put("ID", 2);
map.put("DESC-lq", "desc");
Cart cart = new Cart();
ReflectionUtils.doWithFields(cart.getClass(), field ->{
field.setAccessible(true);
FieldMapping annotation = field.getAnnotation(FieldMapping.class);
if (annotation == null) {
return;
}
if (StringUtils.isBlank(annotation.value())) {
return;
}
Object value = map.get(annotation.value());
field.set(cart, value);
});
System.out.println("cart = " + cart);
}