常规向:
通过反射的操作,先循环遍历实体类中的全部属性,再通过字符串拼接方法将首字母改为大写并与"set"合并,通过invoke方法进行赋值
代码如下
Test test=new Test();
//给test对象赋值
for(int i=0;i<f.length;i++){
//获取属相名
String attributeName=f[i].getName();
//将属性名的首字母变为大写,为执行set/get方法做准备
String methodName=attributeName.substring(0,1).toUpperCase()+attributeName.substring(1);
try{
//获取Test类当前属性的setXXX方法(私有和公有方法)
/*Method setMethod=Test.class.getDeclaredMethod("set"+methodName);*/
//获取Test类当前属性的setXXX方法(只能获取公有方法)
Method setMethod=Test.class.getMethod("set"+methodName,String.class);
//执行该set方法
setMethod.invoke(test,attributeName+"方法赋值");
}catch (NoSuchMethodException e) {
try {
Method setMethod=Test.class.getMethod("set"+methodName,int.class);
setMethod.invoke(test,123);
} catch (Exception e2) {
f[i].set(test,attributeName+"直接赋值");
}
}
}
<