import java.lang.reflect.Method;
public class ReflectHelper {
public static <E> Object reflectObj(Class<E> c,String str) throws Exception{
String[] strArrray = str.split(",");
Class classType = Class.forName(c.getName());
Method[] methodArray = classType.getDeclaredMethods();
E e = c.newInstance();
int j = 0;
for(int i=0;i<methodArray.length;i++){
if((methodArray[i].getName().substring(0,3).equalsIgnoreCase("set"))){
if(j<strArrray.length){
Class[] type = methodArray[i].getParameterTypes();
System.out.println(type[0].getName());
if(type[0].getName().equals("java.lang.String")){
methodArray[i].invoke(e,strArrray[j]);
}
if(type[0].getName().equals("int")){
methodArray[i].invoke(e,Integer.parseInt(strArrray[j]));
}
if(type[0].getName().equals("double")){
methodArray[i].invoke(e,Double.parseDouble((strArrray[j])));
}
j++;
}
}
}
return e;
}
}
java 反射 根据字符串给字段赋值
最新推荐文章于 2024-05-13 10:35:17 发布