快速了解反射的使用

1.通过反射得到类
Class clazz = A.Class;得到一个A类clazz = class A;
A a = new A()a.getClass(); 也是得到一个A类,a.getClass()=class A;
Class t = Class.forName(“animal.A”);括号里写类的路径;t = class A;
2.通过反射调用类里的成员变量
Field f = a.getField(“a”);括号里写成员变量名可以得到类A的成员变量
f.set(a,0)对类A的成员变量赋值
f.get(a)得到类A的成员变量a的值
f.getType()可以得到a的数据类型
3.通过反射调用类里的方法
Method method = a.getMethod(“dog”, int.class);得到带参的dog方法Method method = a.getMethod(“dog”);得到不带参的dog方法
method.invoke(a.newInstance())通过实例化对象调用方法

代码案例

   public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, NoSuchFieldException, InstantiationException {
       //getClass()和class的区别
       Class clazz = Animals.class;
       Animals a = new Animals();
       System.out.println(clazz+"分别的得到两个类名 "+a.getClass());
       System.out.println("得到类的全部名称:"+clazz.getName());
       System.out.println("得到类名:"+clazz.getSimpleName());
       Field field = clazz.getField("a");
       //设置类animal的成员变量的值
       field.set(a,0);
       //得到成员变量的值
       System.out.println(field.get(a));
       System.out.println(Arrays.toString(clazz.getFields()));
       System.out.println("返回a的类型:"+field.getType());

//        Method method = clazz.getMethod( "animal");
//        获取animal的dog(int a)方法
       Method method2 = clazz.getMethod("dog", int.class);
//        实例化对象并传入参数
       method2.invoke(clazz.newInstance(),6);

       //动态加载类,获取当前类的对象
       Class t = Class.forName("yushiweektwo.Polymorphism.Animals");
       //获取animal类的dog()方法
       Method method3 = t.getMethod("dog");
       //通过实例化的对象,调用无参的方法
       method3.invoke(t.newInstance());

       Class c = Human.class;
   }
}
class Animals {
   public int a,b;
   public String i,v;
   public Animals() {
       System.out.println("动物在叫");
   }
   public void cat() {
       System.out.println("小猫在叫");
   }
   public void dog() {
       System.out.println("狗在吃shit");
   }
   public void dog(int a) {
       System.out.println("我这是带有形参的狗");
   }
}
interface Human {
   /**
    * 吃的意思
    */
   void eat();
}

输出结果

class yushiweektwo.Polymorphism.Animals分别的得到两个类名 class yushiweektwo.Polymorphism.Animals
得到类的全部名称:yushiweektwo.Polymorphism.Animals
得到类名:Animals
0
[public int yushiweektwo.Polymorphism.Animals.a, public int yushiweektwo.Polymorphism.Animals.b, public java.lang.String yushiweektwo.Polymorphism.Animals.i, public java.lang.String yushiweektwo.Polymorphism.Animals.v]
返回a的类型:int
动物在叫
我这是带有形参的狗
动物在叫
狗在吃shit

Process finished with exit code 0```
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值