java 反射-feild

import java.lang.reflect.Field;

/**
 * @author dell
 *
 */
public class FieldTest {

    class point{
         private int xx;
         public int yy;
         public point(int x,int y){  
            this.xx=x;
            this.yy=y;
        }
    }
    public static void main(String[] args) throws Exception {
        FieldTest f=new FieldTest();
        FieldTest.point p=f.new point(3,5);
        //获取对象p的yy属性值
        Field field= p.getClass().getField("yy");
        //field :p.getClass() 是类 ,所以field是类上的属性,不是对象p的属性,打印出来的
        //不是5 而是 public int com.hlmedicals.app.test.api.ssz.FieldTest$point.yy
        System.out.println(field);
        //要想获取对象的属性 我们先要获取类上的属性,在通过这个类上的属性.get(对象名称) 获取对象的属性值
        System.out.println(field.get(p));
        
        //获取对象p的xx属性值  注意xx是私有的
        
        //下面 会报Exception in thread "main" java.lang.NoSuchFieldException: xx
        //原因是xx是私有的 ,获取类的属性时候 不能用 getfeild 得用getDeclaredField
//        Field fieldxx=p.getClass().getField("xx");
//        System.out.println(fieldxx.get(p));
        Field fieldxx=p.getClass().getDeclaredField("xx");
        //我们这样还是不能把私有的属性值拿出来 回报java.lang.IllegalAccessException:
        //Class com.hlmedicals.app.test.api.ssz.FieldTest can not access a member of class com.hlmedicals.app.test.api.ssz.FieldTest$point with modifiers "private
        //System.out.println(fieldxx.get(p));
        //我们要在获取私有属性前 ,设置setAccessible(true) 这样我们能取到3
        fieldxx.setAccessible(true);
        System.out.println(fieldxx.get(p));
    }
}    

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值