话不多说,直接上码
方式一,通过Field类获取
String calssName = "com.xxx.xxx.CacheLoader";
Class clazz = Class.forName(className);
Object obj = clazz.newInstance();
// 获取对象属性
Fields[] fields = clazz.getDeclaredFields();
for(Field field: fields){
String name = field.getName();
field.setAccessible(true); // 私有属性必须设置访问权限
Object resultValue = field.get(obj);
// 这里可以编写你的业务代码
System.out.println(name + ": " + resultValue);
}
方式二:通过Method类获取
Class<UserEntity> clazz = UserEntity.class;
Object obj = clazz.newInstance();
// 获取对象属性
Field[] fields = clazz.getDeclaredFields();
for(Field field: fields){
String fieldName = field.getName();
String upperChar = fieldName.substring(0,1).toUpperCase();
String anotherStr = fieldName.substring(1);
String methodName = "get" + upperChar + anotherStr;
Method method = clazz.getMethod(methodName, new Class[]{});
method.setAccessible(true);
Object resultValue = method.invoke(obj, new Object[]{});
// 这里可以编写你的业务代码
System.out.println(fieldName + ": " + resultValue);
}