JAVA反射之 Field (属性)

主要方法:

public static void main(String[] args) throws Exception {
        Class<?> clazz = Class.forName("Person");
        //得到类中所有方法,返回一个数组
        Field[] fileds = clazz.getFields();
        //得到所有方法包括私有方法
        Field[] fields2 = clazz.getDeclaredFields();
        //得到方法
        Field field = clazz.getDeclaredField("name");
        //暴力访问,访问私有属性
        field.setAccessible(true);
        //通过类实例化对象,通过调用类的无参构造器去实例化对象
        Object object = clazz.newInstance();
        //给对象属性赋值
        field.set(object, "hhh");
        //对象类型
        Class s = field.getType();//class java.lang.String
        System.out.println(s);
        //对象名称
        field.getName();
        //获取对象属性值
        field.get("name");
    }

暴力访问会破坏对象的封装性,解决方法为:

//破坏封装性,解决方式(内省机制):
        Class<?> clazz1 = Class.forName("Person");
        // 创建对象
        Object person = clazz1.newInstance();
        // 获得属性描述器
        PropertyDescriptor propertyDescriptor = new PropertyDescriptor("setName", clazz1);
        // 获得set方法
        Method setMethod = propertyDescriptor.getWriteMethod();
        // 调用方法 person.setName("jack");
        setMethod.invoke(person, "jack");
        System.out.println(person);

 

转载于:https://www.cnblogs.com/huanghuanghui/p/10161826.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值