传统型程序员必备技能3——反射

反射
反射:(程序运行时,动态加载类,获取类的信息,从而使用类及其对象的变量和方法)
将类的各个部分重新封装成一个Class类 对象,然后通过这个class类 对象操作其对应的类(获取、修改), 这就是反射机制。
在这里插入图片描述

带Declared可以获取包括public及public以外的所有,Field、Constructor、method

<--Field-->
Field[] getFields()
Field getField(String name) //只能获取public的

Field[] getDeclaredFields()
Field getDeclaredField(String name)//能获取所有

Field.setAccessible(true) //暴力反射

field1.get() //获取值

<--Method-->
Method[] getMethods()
Method getMethod(String name) //只能获取public的

Method[] getDeclaredMethods()
Method getDeclaredMethod(String name)//能获取所有

method.invoke();//执行方法

<--Constructor-->
Constructor[] getConstructors()
Constructor getConstructor(String name) //只能获取public的

Constructor[] getDeclaredConstructors()
Constructor getDeclaredConstructor(String name)//能获取所有

Constructor.newInstance();//执行,创建实例

Constructor.newInstance();

method.invoke();

暴力反射: Field.setAccessible(true)【能获取private 的值】
实际上setAccessible是启用和禁用访问安全检查的开关

举例:

    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        GoodsTest goods = new GoodsTest();
        goods.setId("1");

        Field id = goods.getClass().getDeclaredField("id");
        Field goodsName = goods.getClass().getDeclaredField("goodsName");
        goodsName.set(goods,"张飞");
        //Field.setAccessible(true);
        Object o = id.get(goods);
        Field[] declaredFields = goods.getClass().getDeclaredFields();
        Object o1 = declaredFields[0].get(goods);
        String name = declaredFields[0].getName();
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值