您的位置:首页 > 编程语言 > Java开发

java学习之内省

2016-01-23 23:54 579 查看
反射加内省解决耦合问题

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: