首页 > 代码库 > 反射实现读取文本信息进行对象的动态创建

反射实现读取文本信息进行对象的动态创建

 1 public class TestReflectApp {
 2 
 3     public static void main(String[] args) throws Exception {
 4         //
 5         InputStream is = new FileInputStream("D:\\eclipse-workspace-bigdata4\\Java25\\src\\objects.properties");
 6 //        byte[] bytes = new byte[is.available()];
 7 //        is.read(bytes);
 8 //        //is.close();
 9         //System.out.println(new String(bytes));//注意读取的话出现读到文件末尾,后面进行加载的话内容为空
10         Properties prop = new Properties();
11         prop.load(is);
12         
13         //
14         String objClass = prop.getProperty("object.class");
15         Class clazz = Class.forName(objClass);
16         Object obj = clazz.newInstance();
17         
18         //name
19         String propName = prop.getProperty("object.prop1.name");
20         String propValue = http://www.mamicode.com/prop.getProperty("object.prop1.value");
21         Field f = clazz.getDeclaredField(propName);
22         if(f.getType() == String.class){
23             f.setAccessible(true);
24             f.set(obj, propValue);
25         }
26         
27         
28         //name
29         propName = prop.getProperty("object.prop2.name");
30         propValue = http://www.mamicode.com/prop.getProperty("object.prop2.value");
31         f = clazz.getDeclaredField(propName);
32         if(f.getType() == int.class){
33             f.setAccessible(true);
34             Integer i = Integer.parseInt(propValue) ;
35             f.set(obj, i);
36         }
37         
38     }
39 
40 }

2、文本文件(放在根目录下)

  文件名:objects.properties

  object.class=com.it18zhang.java25.Person
  object.prop1.name=name
  object.prop1.value=http://www.mamicode.com/tomas
  object.prop2.name=age
  object.prop2.value=http://www.mamicode.com/20

反射实现读取文本信息进行对象的动态创建