TmallASCPPurchaseSaleStorageEntity entity = new TmallASCPPurchaseSaleStorageEntity();
Field[] fields = entity.getClass().getDeclaredFields();
for (Field field : fields) {
try {
String name = field.getName();
char[] chars = name.toCharArray();
chars[0] -= 32; //转换第一个字符为大写
name = String.valueOf(chars);
Method method = entity.getClass().getDeclaredMethod("set"+name, String.class);
method.invoke(entity, "xxx"); //赋值
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
}
System.err.println(entity.jsonData());
类成员的字段属性需要有get/set方法; 应用场景可以在属性上加上自定义的注解,然后根据自己的业务情况进行扩展。
一、getFields()与getDeclaredFields()区别:
getFields()只能访问类中声明为公有的字段,私有的字段它无法访问,能访问从其它类继承来的公有方法.
getDeclaredFields()能访问类中所有的字段,与public,private,protect无关,不能访问从其它类继承来的方法
二、getMethods()与getDeclaredMethods()区别:
getMethods()只能访问类中声明为公有的方法,能访问从其它类继承来的公有方法.
getDeclaredFields()能访问类中所有的字段,与public,private,protect无关,不能访问从其它类继承来的方法
三、getConstructors()与getDeclaredConstructors()区别:
getConstructors()只能访问类中声明为public的构造函数.
getDeclaredConstructors()能访问类中所有的构造函数,与public,private,protect无关