我简单写了一下
package action;
import javalangreflectField;
import javalangreflectInvocationTargetException;
import javalangreflectMethod;
public class Test {
/
@param args
/
//这是测试主方法
public static void main(String[] args) {
Test test = new Test();
CacheNumber ch = (CacheNumber) testcreateObj(CacheNumberclass,
"capacity=1,count=2,name=wang,montey=213");
Systemoutprintln(chgetCapacity());
Systemoutprintln(chgetName());
Systemoutprintln(chgetCount());
}
public Object createObj(Class cl, String keyAndValue) {
Object te = null;
try {
Class cla = ClassforName(clgetName());
te = clanewInstance();
String[] valueAndName = keyAndValuesplit(",");
for (int i = 0; i < valueAndNamelength; i++) {
Field[] field = clagetDeclaredFields();
for (int k = 0; k < fieldlength; k++) {
Class[] paraTypes = new Class[] { field[k]getType() };
String name = valueAndName[i]substring(0, valueAndName[i]
indexOf("="));
String value = valueAndName[i]substring(valueAndName[i]
indexOf("=") + 1, valueAndName[i]length());
if (field[k]getName()equals(name)) {
String fieldSetter = "set"
+ namesubstring(0, 1)toUpperCase()
+ namesubstring(1, namelength());
Method method = clagetMethod(fieldSetter, paraTypes);
Object[] values = null;
if (field[i]getType()==intclass) {
values = new Integer[] { IntegervalueOf(value) };
}
if (field[i]getType()==Stringclass) {
values = new String[] { value };
}
if (field[i]getType()==doubleclass) {
values = new Double[] { DoublevalueOf(value) };
}
if(field[i]getType()==shortclass){
values = new Short[]{ShortvalueOf(value)};
}
if(field[i]getType()==longclass){
values = new Long[]{LongvalueOf(value)};
}
methodinvoke(te, values);
}
}
}
} catch (ClassNotFoundException e) {
eprintStackTrace();
} catch (SecurityException e) {
eprintStackTrace();
} catch (NoSuchMethodException e) {
eprintStackTrace();
} catch (IllegalArgumentException e) {
eprintStackTrace();
} catch (IllegalAccessException e) {
eprintStackTrace();
} catch (InvocationTargetException e) {
eprintStackTrace();
} catch (InstantiationException e) {
eprintStackTrace();
}
return te;
}
}
//这是你的CacheNumber我又加了几个类型的属性
package action;
public class CacheNumber {
private int capacity;
private int count;
private String name;
private double montey;
public double getMontey() {
return montey;
}
public void setMontey(double montey) {
thismontey = montey;
}
public String getName() {
return name;
}
public void setName(String name) {
thisname = name;
}
public int getCount() {
return count;
}
public void setCount(int count) {
thiscount = count;
}
// 默认构造器
public CacheNumber() {
}
public CacheNumber(int capacity, int count) {
thiscapacity = capacity;
thiscount = count;
}
public int getCapacity() {
return capacity;
}
public void setCapacity(int capacity) {
thiscapacity = capacity;
}
public static void main(String[] args) {
}
}
写的很简单,你看哪块不合适再改一改吧,思路就是这么个思路
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)