通过反射机制调用set方法,给Bean的属性赋值
需要导入的引用
import java.lang.reflect.Method;
实体类对象:
@Data
public class TestFanShe {
private String aaa001;
private String aaa002;
private String aaa003;
private String aaa004;
}
public static void main(String[] args) {
// 创建TestFanShe对象
TestFanShe user = new TestFanShe();
for (int i = 1; i < 5; i++) {
// 调用赋值方法
setPropertyValue(user,"Aaa00" + i ,String.valueOf(i),String.class);
//调用取值方法
System.out.println(getPropertyValue(user,"Aaa00" + i));
}
}
/**
* 赋值
* @param surgery 要赋值的类对象
* @param propertyName 类属性名称 首字母大写
* @param propertyValue 类属性值
* @param propertyClass 属性对应的class 例:String 传 String.class
* @throws Exception
*/
private static <T> void setPropertyValue(T surgery, String propertyName, Object propertyValue, Class<?> propertyClass) {
Class<?> classZ = surgery.getClass();
try {
Method method = classZ.getMethod("set" + propertyName, propertyClass);
method.invoke(surgery, propertyValue);
} catch (Exception e) {
}
}
/**
* 取值
* @param surgery 要取值的类对象
* @param propertyName 类属性名称 首字母大写
*/
private static <T> Object getPropertyValue(T surgery, String propertyName) {
Class<?> classZ = surgery.getClass();
try {
// 获取方法对象
Method method = classZ.getMethod("get" + propertyName);
// 调用方法,获取属性值
return method.invoke(surgery);
} catch (Exception e) {
return null;
}
}