码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-04-29 18:49:49      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:tde   void   access   cli   objc   style   eclips   stat   work   

 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 = 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 = 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=tomas
  object.prop2.name=age
  object.prop2.value=20

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

标签:tde   void   access   cli   objc   style   eclips   stat   work   

原文地址:http://www.cnblogs.com/yihaifutai/p/6785702.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!