模型
@Data
@ToString
public class TestReflectModel {
@TestReflect(fieldName = "myname")
private String name;
private String adress;
}
注解
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.PARAMETER})
public @interface TestReflect {
String fieldName() default "";
}
方法和测试
public class TestReflectMain {
public static void main(String[] args) throws InstantiationException, IllegalAccessException {
Map<String, String> map = new HashMap<>();
map.put("myname","旺旺");
map.put("adress","安阳");
TestReflectModel testReflectModel = convertToModel(map);
System.out.println(testReflectModel);
}
private static TestReflectModel convertToModel(Map<String,String> map) throws IllegalAccessException, InstantiationException {
Class<TestReflectModel> clazz = TestReflectModel.class;
TestReflectModel model = clazz.newInstance();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
TestReflect validator = field.getAnnotation(TestReflect.class);
if (!field.isAccessible()) {
field.setAccessible(true);
}
if (validator == null) {
field.set(model,map.get(field.getName()));
continue;
}
String name = validator.fieldName();
if(StringUtils.isNotBlank(name)){
field.set(model,map.get(name));
}
}
return model;
}
}