java学习之内省
2016-01-23 23:54
579 查看
反射加内省解决耦合问题
配置文件bean.properties
#\u914D\u7F6EJavaBean\u7684\u5168\u540D
dog=com.gh.introspector.Dog
dog.name=\u5C0F\u767D
dog.age=3
package com.gh.introspector; /** * JavaBean * @author ganhang * */ public class Dog { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Dog [name=" + name + ", age=" + age + "]"; } }
package com.gh.introspector; import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.util.Properties; /** * 工厂类 * @author ganhang * */ public class DogFactory { //属性文件操作工具类 private static Properties config = new Properties(); static { // 读取属性文件到输入流 InputStream is = Thread.currentThread() .getContextClassLoader().getResourceAsStream("bean.properties"); //注意:配置文件放src下可以不用写包名,如果放包里面则要写包名,否者下面报空指针 try { // 加载输入流 config.load(is); is.close(); } catch (IOException e) { e.printStackTrace(); } } // 同样不想与Dog耦合,直接依赖,所以用配置文件创建dog public static Dog getDog(String name) { // 根据key获取values String classname = config.getProperty(name); try { // 根据类全名获取类信息Class对象 Class dogClass = Class.forName(classname); // 实例化对象 Dog dog = (Dog) dogClass.newInstance(); // 内省:获取bean信息 BeanInfo beanInfo = Introspector.getBeanInfo(dogClass); // 通过bean信息获得所有属性描述器(数组) PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors(); // 循环遍历属性描述器 for (PropertyDescriptor pd : pds) { if ("name".equals(pd.getName())) { String nameValue = config.getProperty("dog.name"); // 通过属性描述器获得改属性上的写操作方法(set方法) Method method = pd.getWriteMethod(); // 在dog对象上调用方法 method.invoke(dog, nameValue); } else if ("age".equals(pd.getName())) { String ageValue = config.getProperty("dog.age"); // 通过属性描述器获得改属性上的写操作方法(set方法) Method method = pd.getWriteMethod(); // 在dog对象上调用方法,注意String转int method.invoke(dog, Integer.parseInt(ageValue)); } } return dog; } catch (Exception e) { e.printStackTrace(); } return null; } }
配置文件bean.properties
#\u914D\u7F6EJavaBean\u7684\u5168\u540D
dog=com.gh.introspector.Dog
dog.name=\u5C0F\u767D
dog.age=3
相关文章推荐
- java学习之反射
- java学习之动态代理模式
- java中的length属性和length()方法和size()方法
- java学习之观察者设计模式
- java学习之url
- 记录ubuntu14安装jdk的过程
- junit入门
- java学习之线程池的实现
- Java多线程梳理
- java学习之生产者和消费者案例
- java之文件夹遍历
- Java反射机制
- java学习之线程的操作方法
- java并发编程——ExecutorService\join\yield
- java学习之IO装饰设计模式
- [JavaEE]JaveEE遇到的的问题
- java学习之IO文件分割
- java学习之IO对象流
- java中的String类常量池详解
- java学习之实现文件的复制