项目结构图:
pojo类
package reflect;
public class Point {
private String x;
private String y;
public String getX() {
return x;
}
public void setX(String x) {
this.x = x;
}
public String getY() {
return y;
}
public void setY(String y) {
this.y = y;
}
public Point(String x, String y) {
super();
this.x = x;
this.y = y;
}
}
测试类
public static void main(String[] args) throws Exception{
InputStream is = ReflectionTest.class.getResourceAsStream("config.properties");
// InputStream is = ReflectionTest.class.getClassLoader().getResourceAsStream("reflect/config.properties");//从classPath开始找,使用相对路径
Properties pr = new Properties();//Properties 类表示了一个持久的属性集。Properties 可保存在流中或从流中加载。属性列表中每个键及其对应值都是一个字符串。
pr.load(is);//从输入流中读取属性列表
System.out.println(pr.getProperty("x")+" "+pr.getProperty("y"));
Point p = new Point("111", "222");
String propertyName = "x";
PropertyDescriptor pd = new PropertyDescriptor(propertyName, p.getClass());//PropertyDescriptor 描述 Java Bean 通过一对存储器方法导出的一个属性。
Method method = pd.getReadMethod();// 获得应该用于读取属性值的方法。
Object obj = method.invoke(p);
System.out.println(obj);
Method method2 = pd.getWriteMethod();//获得应该用于写入属性值的方法。
method2.invoke(p,"ccc");
System.out.println(p.getX());
}
config.properties
x=aaa
y=bbb
输出结果:
aaa bbb
111
ccc