反射的常用方法

反射

获取对象的三种方法

反射主要是针对于类加载器阶段的(仅仅代表自己的见解,如有错误请多多谅解)

 截图来自黑马程序员

反射的常用方法

获取构造方法:

 getConstructors()                                   //获取全部类的构造方法
 ​
 getConstructors(无)                                //获取无参构造的
        Class<?> aClass = Class.forName("tcu.se.entity.Student");
         Constructor<?> constructor = aClass.getConstructor();
         constructor.newInstance();
 ​
 getConstructors(String.class,int.class);          // 获取有参的构造方法
          Class<?> aClass = Class.forName("tcu.se.entity.Student");
          Constructor<?> constructor2 = aClass.getConstructor(int.class,String.class);
          constructor2.newInstance(3,"slf");

成员方法

 getMethods()                                        //获取公开的所有方法,以及从父类中继承的方法。
 ​
 getDeclareMethods()                             //获取本类的所有方法,包括私有方法,但不包括从父类中继承的
  //单个无参数无返回值的方法
   getMethod()  :
         Class cls=Class.forName("tcu.se.entity.Student");
         Object boj=cls.newInstance();          //创建对象
         Method method1=cls.getMethod("show");  //获取方法
         method1.invoke(boj);                  //第一个参数是对象,利用对象来调用方法
   
  //单个有参数无返回值的方法
   getMethod() 
          Class cls=Class.forName("tcu.se.entity.Student");
         Object boj=cls.newInstance();
         Method method1=cls.getMethod("show2",int.class);
         method1.invoke(boj,34);
 ​
 ​
   //私有方法
 getDeclareMethod()
         Class cls=Class.forName("tcu.se.entity.Student");
         Object boj=cls.newInstance();
         Method method1=cls.getDeclaredMethod("show2",int.class);
         method1.setAccessible(true);     //但在访问中必须要设置private失效setAccissible(true);
         method1.invoke(boj,34);
 ​
   //静态方法
    // 因为静态方法类名。方法名
         Object boj=cls.newInstance();
         Method method1=cls.getMethod("show2",int.class);   // 因为静态方法类名。方法名
         method1.invoke(null,34);
     
  //任何对象的通用方法
     invokeAny(Object obj,String methodNme,Class<?>[] type,Object...args)
             对象        方法名           方法的参数           参数的值

成员属性

 getFields()                     //获取了的公共成员变量
 getDeclareFields()              //获取本类所有的变量,包括私有变量
     
     //成员方法
 getDeclareField()
     Class<?> aClass = Class.forName("tcu.se.entity.Student");
         Field name =aClass.getDeclaredField("name");
         Object o = aClass.newInstance();
         name.set(o,"张三");
         System.out.println(name.get(o));
     //私有的成员方法
 getDeclareField()
         Class<?> aClass = Class.forName("tcu.se.entity.Student");
         Field name =aClass.getDeclaredField("name");
         name.setAccessible(true);
         Object o = aClass.newInstance();
         name.set(o,"张三");
         System.out.println(name.get(o));

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

折耳狐

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值