JAVA反射机制获取类和方法

来源:互联网 发布:网络技术开发是什么 编辑:程序博客网 时间:2024/06/06 00:02

问题:

  1. 可以通过String类型的方法名调度方法么?
  2. 可以获得特定的类么?比如当前类,隔壁的类,类的新实例,当前实例?
  3. 多态的函数具有相同的名字、不同的参数类型,如何区分呢?
  4. 如何获取指定类的参数类型等信息?

带着这些问题,我做了一些实践。总结如下:

答案:Java提供反射机制,java.lang.reflect.*,可以实现包含不限于以上功能。

下面是一些常用的通过反射获取类、调用方法的例子。关于成员、构造器的调用同理可得。想了解更多,可以查看接口文档。

[java] view plaincopy
  1. package com.taobao.tuisi;  
  2.   
  3. public class Actions{  
  4.   
  5. public void tempMethod(Long userId){  
  6.   
  7. System.out.println(“我是JAVA反射测试方法,我被invoke了” + userId);  
  8.   
  9. }  
  10.   
  11.     public void temp() throws Exception{  
  12.   
  13. //1.获得class  
  14.   
  15.        //获得类的当前实例  
  16.   
  17.        Actions a = this;  
  18.   
  19.        System.out.println(a);  
  20.   
  21.        //输出 com.taobao.tuisi.Actions
    EnhancerByCGLIB
    dff89711@c2ccac  
  22.   
  23.        //获得指定类的新实例  
  24.   
  25.        Actions b = Actions.class.newInstance();  
  26.   
  27.        System.out.println(b);  
  28.   
  29.        //输出 com.taobao.tuisi.Actions@1e4fede  
  30.   
  31. //  
  32.   
  33.        //通过类型获得类  
  34.   
  35.        Class boolType = Boolean.class;  
  36.   
  37.        System.out.println(boolType);  
  38.   
  39.        //输出 class java.lang.Boolean  
  40.   
  41. //  
  42.   
  43.        //通过变量获得类  
  44.   
  45.        String stringExample = “”;  
  46.   
  47.        Class stringType = stringExample.getClass();  
  48.   
  49.        System.out.println(stringType);  
  50.   
  51.        //输出class java.lang.String  
  52.   
  53. //  
  54.   
  55.        //由名字获得类  
  56.   
  57.        Class<?> c = Class.forName(“com.taobao.tuisi.Actions”);  
  58.   
  59.        System.out.println(c);  
  60.   
  61.        //输出 class com.taobao.tuisi.Actions  
  62.   
  63. //  
  64.   
  65. //2.关于method  
  66.   
  67.        //由函数名和参数类型得到函数  
  68.   
  69.        Long userId = 9999l;  
  70.   
  71.        Method method = Actions.class.getDeclaredMethod(“tempMethod”, userId.getClass());  
  72.   
  73.        System.out.println(method);  
  74.   
  75.        //输出 public void com.taobao.tuisi.Actions.tempMethod(java.lang.Long)  
  76.   
  77. //  
  78.   
  79.        //通过类、参数值调用指定函数  
  80.   
  81.        Actions actions = new Actions();  
  82.   
  83.        Long args[] = new Long [1];  
  84.   
  85.        args[0] = userId;  
  86.   
  87.        method.invoke(actions, args);  
  88.   
  89.        //输出  我是JAVA反射测试方法,我被invoke了9999  
  90.   
  91.     }  
  92.   
  93. }  
0 0
原创粉丝点击