240
正在加载今日诗词....

从properties中读取配置创建对象

主要做两个事,从properties配置文件中读取信息,通过反射创建对象

思路主要有两种,遍历得到的属性集合,然后设置类的属性

遍历类的属性集合,从配置文件中读取(不推荐,因为类的属性有多样化,会报错)

try {
   Properties prop = new Properties();
   prop.load(new FileInputStream(
     "F:\\user.properties"));
   Class class1 = Class.forName("com.zlkj.config.User1");
   Object newInstance = class1.newInstance();
//这样就可以拿到本类中公有和私有方法
   Field[] fields = class1.getDeclaredFields();
   for (Field field : fields) {
    field.setAccessible(true);
    field.set(newInstance, prop.getProperty(field.getName()));
   }
   
   System.out.println(newInstance.toString());
  } catch (Exception e) {
   e.printStackTrace();
  }

以上方法要注意几点:

  • 注入的类的属性要是String类,如果是其他类,要调用相应的方法,不然会报错;
  • 有时候可能要拿父类的属性,调用 getSuperClass().getDeclaredFields()

本文由博客一文多发平台 OpenWrite 发布!

posted @ 2019-10-28 22:23  小鱼吃猫  阅读(1388)  评论(0编辑  收藏  举报