反射-访问类变量的方法


   通过java的反射机制,可以轻松获得类变量的所有信息,并且可以修改变量的值,如果这些属性是private活protected的,则必须设置setAccessible(true)的方法,否则会抛出IllegalAccessException异常,如果java安全机制,则可能会抛出securityException异常


import java.lang.reflect.Field;


public class fieldTest {
	public static void main(String[] args) throws IllegalAccessException{
		House house=new House("gdgdg",160,300,"peking wangfujing","wang");
		Class c=house.getClass();
		Field[] fields=c.getDeclaredFields();
		System.out.println("共有成员变量:"+fields.length);
		System.out.println("-----------------------------");
		
		for(Field field:fields){
			field.setAccessible(true);
			Class t=field.getType();
			if (t==String.class){
				System.out.println(field.getName()+":"+field.get(house));
			}
			if(t ==int.class){
				System.out.println(field.getName()+":"+field.getInt(house));
			}
			
		}
		System.out.println("\n 变量设置新值");
		System.out.println("----------------------");
		for(Field field:fields){
			field.setAccessible(true);
			String n=field.getName();
			if (n.equalsIgnoreCase("owner")){
				field.set(house,"wang liang");
			}
			if (n.equalsIgnoreCase("space")){
				field.set(house,field.getInt(house)*2);
			}
			if (n.equalsIgnoreCase("price")){
				field.set(house,field.getInt(house)*2);
			}
			if (n.equalsIgnoreCase("address")){
				field.set(house,"fujian yongding");
			}
			if (n.equalsIgnoreCase("name")){
				field.set(house,"wanglu house");
			}
		    
		}
		for(Field field:fields){
			System.out.println(field.getName()+":"+field.get(house));
		}
	}

}


 class House{
	public String owner;
	protected int space;
	private int price;
	private String address;
	private static String name;
	public House(){}
		public House(String owner,int space,int price,String address,String n){
			this.owner=owner;
			this.space=space;
			this.price=price;
			this.address=address;
			name=n;
		}	
}


结果:


house的实例获得了class对象,通过class对象获取的house的所有属性,并将变量的名字和字值打印出来,然后通过设置setAccessible(true)方法,修改house的公共变量和私有变量。



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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值