package chaperter2.question3;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import chaperter2.question1.person;
public class StoreAttrToInstance {
private String temp;
private person ps =new person();
private Class clazz = ps.getClass();
public static void main(String[] args) {
// TODO 自动生成的方法存根
StoreAttrToInstance sati = new StoreAttrToInstance();
sati.ReadFile();
System.out.println(sati.toString());
}
private void ReadFile() {
try {
FileReader fr = new FileReader(new File("src\\chaperter2\\question2\\cout.txt"));
BufferedReader br = new BufferedReader(fr);
while((temp=br.readLine())!=null) {
Cuttext(temp);
}
br.close();
fr.close();
}catch(Exception e) {
e.printStackTrace();
}
}
private void Cuttext(String line){
String[] values= line.split("=");
String value =values[0].trim();
String mn="set"+values[0];
String value1 = values[1].trim();
try {
Method[] method=clazz.getDeclaredMethods();
for(Method m:method){
if(m.getName().equals(mn)){
Class[] paramType=m.getParameterTypes();
String type=paramType[0].getCanonicalName();
m.invoke(ps,Class.forName(type).getConstructor(String.class).newInstance(value1));
return;
}
}
}catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
}
public String toString(){
return "idNo="+ps.getidNo()+"\nname="+ps.getname()+"\nage="
+ps.getage()+"\nsex="+ps.getsex()+"\nisMerried=" +ps.getisMerried();
}
}
反射修改属性
最新推荐文章于 2024-05-23 21:04:14 发布