Java反射实例(实战方能理解jdk的各种方法)

来源:互联网 发布:山东网络作家协会 编辑:程序博客网 时间:2024/06/05 15:06

什么是反射?反射有什么用处?

1. 什么是反射?

“反射(Reflection)能够让运行于JVM中的程序检测和修改运行时的行为。”这个概念常常会和内省(Introspection)混淆,以下是这两个术语在Wikipedia中的解释:

  1. 内省用于在运行时检测某个对象的类型和其包含的属性;
  2. 反射用于在运行时检测和修改某个对象的结构及其行为。

从它们的定义可以看出,内省是反射的一个子集。有些语言支持内省,但并不支持反射,如C++。

反射和内省

内省示例:instanceof 运算符用于检测某个对象是否属于特定的类。

1
2
3
4
if(objinstanceofDog) {
    Dog d = (Dog) obj;
    d.bark();
}

反射示例:Class.forName()方法可以通过类或接口的名称(一个字符串或完全限定名)来获取对应的Class对象。forName方法会触发类的初始化。

1
2
3
4
5
// 使用反射
Class<?> c = Class.forName("classpath.and.classname");
Object dog = c.newInstance();
Method m = c.getDeclaredMethod("bark",newClass<?>[0]);
m.invoke(dog);

在Java中,反射更接近于内省,因为你无法改变一个对象的结构。虽然一些API可以用来修改方法和属性的可见性,但并不能修改结构。

2. 我们为何需要反射?

反射能够让我们:

  • 在运行时检测对象的类型;
  • 动态构造某个类的对象;
  • 检测类的属性和方法;
  • 任意调用对象的方法;
  • 修改构造函数、方法、属性的可见性;
  • 以及其他。

反射是框架中常用的方法。

例如,JUnit通过反射来遍历包含 @Test 注解的方法,并在运行单元测试时调用它们。(这个连接中包含了一些JUnit的使用案例)

对于Web框架,开发人员在配置文件中定义他们对各种接口和类的实现。通过反射机制,框架能够快速地动态初始化所需要的类。

例如,Spring框架使用如下的配置文件:

1
2
3
<beanid="someID"class="com.programcreek.Foo">
    <propertyname="someField"value="someValue"/>
</bean>

当Spring容器处理<bean>元素时,会使用Class.forName("com.programcreek.Foo")来初始化这个类,并再次使用反射获取<property>元素对应的setter方法,为对象的属性赋值。

Servlet也会使用相同的机制:

1
2
3
4
<servlet>
    <servlet-name>someServlet</servlet-name>
    <servlet-class>com.programcreek.WhyReflectionServlet</servlet-class>
<servlet>

3. 如何使用反射?

让我们通过几个典型的案例来学习如何使用反射。

示例1:获取对象的类型名称。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
packagemyreflection;
importjava.lang.reflect.Method;
 
publicclassReflectionHelloWorld {
    publicstaticvoid main(String[] args){
        Foo f = newFoo();
        System.out.println(f.getClass().getName());        
    }
}
 
classFoo {
    publicvoidprint() {
        System.out.println("abc");
    }
}

输出:

1
myreflection.Foo

示例2:调用未知对象的方法。

在下列代码中,设想对象的类型是未知的。通过反射,我们可以判断它是否包含print方法,并调用它。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
packagemyreflection;
importjava.lang.reflect.Method;
 
publicclassReflectionHelloWorld {
    publicstaticvoid main(String[] args){
        Foo f = newFoo();
 
        Method method;
        try{
            method = f.getClass().getMethod("print",newClass<?>[0]);
            method.invoke(f);
        }catch(Exception e) {
            e.printStackTrace();
        }          
    }
}
 
classFoo {
    publicvoidprint() {
        System.out.println("abc");
    }
}

输出:

1
abc

示例3:创建对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
packagemyreflection;
 
publicclassReflectionHelloWorld {
    publicstaticvoid main(String[] args){
        // 创建Class实例
        Class<?> c = null;
        try{
            c=Class.forName("myreflection.Foo");
        }catch(Exception e){
            e.printStackTrace();
        }
 
        // 创建Foo实例
        Foo f = null;
 
        try{
            f = (Foo) c.newInstance();
        }catch(Exception e) {
            e.printStackTrace();
        }  
 
        f.print();
    }
}
 
classFoo {
    publicvoidprint() {
        System.out.println("abc");
    }
}

示例4:获取构造函数,并创建对象。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
packagemyreflection;
 
importjava.lang.reflect.Constructor;
 
publicclassReflectionHelloWorld {
    publicstaticvoid main(String[] args){
        // 创建Class实例
        Class<?> c = null;
        try{
            c=Class.forName("myreflection.Foo");
        }catch(Exception e){
            e.printStackTrace();
        }
 
        // 创建Foo实例
        Foo f1 = null;
        Foo f2 = null;
 
        // 获取所有的构造函数
        Constructor<?> cons[] = c.getConstructors();
 
        try{
            f1 = (Foo) cons[0].newInstance();
            f2 = (Foo) cons[1].newInstance("abc");
        }catch(Exception e) {
            e.printStackTrace();
        }  
 
        f1.print();
        f2.print();
    }
}
 
classFoo {
    String s;
 
    publicFoo(){}
 
    publicFoo(String s){
        this.s=s;
    }
 
    publicvoidprint() {
        System.out.println(s);
    }
}

输出:

1
2
null
abc

此外,你可以通过Class实例来获取该类实现的接口、父类、声明的属性等。

示例5:通过反射来修改数组的大小。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
packagemyreflection;
 
importjava.lang.reflect.Array;
 
publicclassReflectionHelloWorld {
    publicstaticvoid main(String[] args) {
        int[] intArray = { 1,2,3,4,5};
        int[] newIntArray = (int[]) changeArraySize(intArray, 10);
        print(newIntArray);
 
        String[] atr = { "a","b","c","d","e"};
        String[] str1 = (String[]) changeArraySize(atr, 10);
        print(str1);
    }
 
    // 修改数组的大小
    publicstaticObject changeArraySize(Object obj, intlen) {
        Class<?> arr = obj.getClass().getComponentType();
        Object newArray = Array.newInstance(arr, len);
 
        // 复制数组
        intco = Array.getLength(obj);
        System.arraycopy(obj,0, newArray, 0, co);
        returnnewArray;
    }
 
    // 打印
    publicstaticvoid print(Object obj) {
        Class<?> c = obj.getClass();
        if(!c.isArray()) {
            return;
        }
 
        System.out.println("\nArray length: " + Array.getLength(obj));
 
        for(inti = 0; i < Array.getLength(obj); i++) {
            System.out.print(Array.get(obj, i) + " ");
        }
    }
}

输出:

1
2
3
4
Array length: 10
1 2 3 4 5 0 0 0 0 0
Array length: 10
a b c d e null null null null null

/===================================================
// 反射类的构造函数
//===================================================


<!--
首先,通过Class获取类的字节码
| Class clazz = Class.forName("com.marer.reflect.Person");
|
然后,利用Constructor创建对象
| Constructor c = clazz.getConstructor(null);//获取无参的构造函数
| Constructor c = clazz.getConstructor(String.class);//获取参数为String的构造函数
| Constructor c = clazz.getConstructor(String.class, int.class);//获取参数为String,int的构造函数
| Constructor c = clazz.getDeclaredConstructor(List.class);//获取隐藏为private的构造函数
| c.setAccessible(true);//暴力反射
|
| 创建对象的另外一种途径,反射出类的无参构造函数并创建对象
| Class clazz = Class.forName("com.marer.reflect.Person");
| Person p = (Person) clazz.newInstance();
| 但是当无参的构造函数为private或不存在的时候,反射抛异常
|转载请注明出处:http://blog.csdn.net/nthack5730/article/details/49822819
| 但是可以通过暴力反射获取类的隐藏构造函数
| Constructor.setAccessible(true);

-->



[java] view plain copy
 print?
  1. //解剖类的构造函数,创建类的对象  
  2. public class Demo2 {  
  3.       
  4.     //反射构造函数:public Person()  
  5.     @Test  
  6.     public void test1() throws Exception{  
  7.           
  8.         Class clazz = Class.forName("com.marer.reflect.Person");  
  9.         Constructor c = clazz.getConstructor(null);  
  10.           
  11.         Person person = (Person)c.newInstance(null);  
  12.           
  13.         System.out.println(person.str);  
  14.     }  
  15.       
  16.       
  17.       
  18.     //反射构造函数:public Person(String name)  
  19.     @Test  
  20.     public void test2() throws Exception{  
  21.           
  22.         Class clazz = Class.forName("com.marer.reflect.Person");  
  23.         Constructor c = clazz.getConstructor(String.class);  
  24.           
  25.         Person person = (Person)c.newInstance("测试成功");  
  26.           
  27.         System.out.println(person.str);  
  28.     }  
  29.       
  30.       
  31.       
  32.     //反射构造函数:public Person(String name, int age)  
  33.     @Test  
  34.     public void test3() throws Exception{  
  35.           
  36.         Class clazz = Class.forName("com.marer.reflect.Person");  
  37.         Constructor c = clazz.getConstructor(String.classint.class);  
  38.           
  39.         Person person = (Person)c.newInstance("测试成功",123);  
  40.           
  41.         System.out.println(person.str);  
  42.     }  
  43.       
  44.       
  45.       
  46.     //反射四有的构造函数:private Person(List list)  
  47.     @Test  
  48.     public void test4() throws Exception{  
  49.         Class clazz = Class.forName("com.marer.reflect.Person");  
  50.         Constructor c = clazz.getDeclaredConstructor(List.class);  
  51.           
  52.         c.setAccessible(true);//暴力反射  
  53.           
  54.         Person p = (Person) c.newInstance(new ArrayList());  
  55.           
  56.         System.out.println(p.str);  
  57.     }  
  58.       
  59.       
  60.       
  61.     //创建对象的另外一种途径,反射出类的无参构造函数并创建对象  
  62.     //但是当无参的构造函数为private或不存在的时候,反射抛异常  
  63.     @Test  
  64.     public void test5() throws Exception{  
  65.         Class clazz = Class.forName("com.marer.reflect.Person");  
  66.         Person p = (Person) clazz.newInstance();  
  67.         System.out.println(p);  
  68.         System.out.println(p.str);  
  69.     }  
  70. }  

原创粉丝点击