java反射之成员变量的反射

public class ReflectTest {

    public static void main(String[] args) throws Exception {
    
                //成员变量的反射
		ReflectPoint pt1 = new ReflectPoint(3, 5);
		Field fieldY = pt1.getClass().getField("y");
		System.out.println(fieldY.get(pt1));//5 因为y是公有属性,可以直接得到
		Field fieldX = pt1.getClass().getDeclaredField("x"); 
		fieldX.setAccessible(true);
		System.out.println(fieldX.get(pt1));//3 x是私有属性,使用getDeclaredField,然后setAcces                                                        sible(true)
		changeStringValue(pt1);
		System.out.println(pt1);//aall:aasketaall:itcast
    }
    private static void changeStringValue(Object obj) throws Exception {

		Field[] fields = obj.getClass().getFields();
		for(Field field :fields){
			if(field.getType()==String.class){
				String oldValue = (String) field.get(obj);
				String newValue = oldValue.replace('b', 'a');
				field.set(obj, newValue);
			}
		}
	}
}

public class ReflectPoint {

	private int x;
	public int y;
	public String str1 = "ball";
	public String str2 = "basketball";
	public String str3 = "itcast";
	
	public ReflectPoint(int x, int y) {
		super();
		this.x = x;
		this.y = y;
	}
	
        @Override
	public String toString(){
		
		return str1+":"+str2+":"+str3;
	}	
}



转载于:https://my.oschina.net/projerry/blog/515637

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值