java反射-用类加载器的方式管理资源和配置文件

项目结构图:

 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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值