遍历类对象的所有属性
//可以使用getDeclaredFields()方法获取对象的所有属性
AutoClass autoClass = new AutoClass(); // 先初始化一个类
Field[] fields = autoClass.getClass().getDeclaredFields(); // 获取对象的所有属性
for (Field item : fields) {
String name = item.getName(); // 获取对象属性名
String typeName = item.getGenericType().getTypeName(); // 获取对象属性的类型
System.out.printf("属性名:%s,类型:%s\n", name, typeName);
}
获取属性的get、set方法
// 一般而言每个属性都有其get和set方法
// 通过方法名获取get方法
Method getMethod = autoClass.getClass().getMethod("getId");
// 调用get方法
String invoke = (String) getMethod.invoke(autoClass);
System.out.println(invoke);
// 通过方法名获取set方法,由于set方法是有参数的,所以这里也需要定义set方法的参数类型
Method setMethod = autoClass.getClass().getMethod("setId", String.class);
// 调用set方法
setMethod.invoke(autoClass, "gftz");
System.out.println(autoClass.getId());
// invoke方法中的autoClass表示autoClass这个指定对象调用相应方法
工具类
package utils;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.Date;
/**
* @description: 数据类的相关操作
**/
// 由于为了让这个工具类能够通用,故而用了泛型,对其不了解需要自行百度一下。
public class ObjectOperate {
/**
* 设置数据类对象的属性
* @param obj 数据类对象的实例
* @param name 属性名
* @param type 属性类型名
* @param val 需要存入的属性值
* @throws NoSuchMethodException
* @throws InvocationTargetException
* @throws IllegalAccessException
*/
public void setValues(T obj, String name, String type, Object val) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Method method = null;
// 通过属性类型来获取相应的方法以及强制转化属性值并初始化相应属性
// 这里考虑到了大部分常用的数据类型,可拿来即用。
switch (type){
case "int":
method = obj.getClass().getMethod(name, int.class);
method.invoke(obj,(int)val);
break;
case "short":
method = obj.getClass().getMethod(name, short.class);
method.invoke(obj,(short)val);
break;
case "long":
method = obj.getClass().getMethod(name, long.class);
method.invoke(obj,(long)val);
break;
case "float":
method = obj.getClass().getMethod(name, float.class);
method.invoke(obj,(float)val);
break;
case "double":
method = obj.getClass().getMethod(name, double.class);
method.invoke(obj,(double)val);
break;
case "boolean":
method = obj.getClass().getMethod(name, boolean.class);
method.invoke(obj,(boolean)val);
break;
case "java.lang.String":
method = obj.getClass().getMethod(name, String.class);
method.invoke(obj,(String)val);
break;
case "java.util.Date":
method = obj.getClass().getMethod(name, Date.class);
method.invoke(obj,(Date)val);
break;
case "java.math.BigDecimal":
method = obj.getClass().getMethod(name, BigDecimal.class);
method.invoke(obj,(BigDecimal)val);
break;
}
}
}
使用案例
// 模拟案例数据
List