java反射详解
linking)、动态加载(dynamic loading)等。然而“动态”一词其实没有绝对而普遍适用的严格定义,有时候甚至像对象导向当初被导入编程领域一样,一人一把号,各吹各的调。
ability of the program to examine itself)被称为introspection(内省、内观、反省)。Reflection和introspection是常被并提的两个术语。
给个例子,还原一个类:
public void testReflect() throws ClassNotFoundException, SecurityException, NoSuchMethodException{
Class clazz = Class.forName("cn.reflect.FooInstance");//加载自己写的类
System.out.println("----------------start constructors print-------------------");
Constructor[] constructors = clazz.getDeclaredConstructors();//获取该类中申明的构造函数包括private函数, 但不包括父类的构造函数
for(Constructor cons:constructors){String param ="";for(Class str:cons.getParameterTypes()){param +=str+",";}
System.out.println(Modifier.toString(cons.getModifiers())+" "+cons.getName()+"("+(param.length()>0?param.substring(0, param.length()-1):param)+")"); }
System.out.println("----------------start methods print-------------------");
Method[] methods = clazz.getDeclaredMethods();//获取该类中申明的方法 包括private方法 但不包括父类的方法
for(Method met:methods){String param ="";for(Class str:met.getParameterTypes()){param +=str+",";}
System.out.println(Modifier.toString(met.getModifiers())+" "+met.getReturnType()+" "+met.getName()+"("+(param.length()>0?param.substring(0, param.length()-1):param)+")");}
System.out.println("----------------start parameters print-------------------");
Field[] fields = clazz.getDeclaredFields();//获取该类中申明的成员变量 包括private成员变量, 但不包括父类的成员变量
for(Field fil : fields){System.out.println(Modifier.toString(fil.getModifiers())+" "+fil.getType()+" "+fil.getName());}
}
原文地址:http://www.cnblogs.com/rollenholt/archive/2011/09/02/2163758.html
本篇文章依旧采用小例子来说明,因为我始终觉的,案例驱动是最好的,要不然只看理论的话,看了也不懂,不过建议大家在看完文章之后,在回过头去看看理论,会有更好的理解。
下面开始正文。
【案例1】通过一个对象获得完整的包名和类名
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
package Reflect; /** * 通过一个对象获得完整的包名和类名 * */ class Demo{ //other codes... } class hello{ public static void
Demo demo= new Demo();
System.out.println(demo.getClass().getName());
} } |
【运行结果】:Reflect.Demo
添加一句:所有类的对象其实都是Class的实例。
【案例2】实例化Class类对象
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
|
package Reflect; class Demo{ //other codes... } class hello{ public static void
Class<?> demo1= null ;
Class<?> demo2= null ;
Class<?> demo3= null ;
try { //一般尽量采用这种形式 demo1=Class.forName( "Reflect.Demo" ); } catch (Exception e){
e.printStackTrace(); } demo2= new Demo().getClass(); demo3=Demo. class ;
System.out.println( "类名称 " +demo1.getName()); System.out.println( "类名称 " +demo2.getName()); System.out.println( "类名称 " +demo3.getName()); } } |
【运行结果】:
类名称 Reflect.Demo
类名称 Reflect.Demo
类名称 Reflect.Demo
【案例3】通过Class实例化其他类的对象
通过无参构造实例化对象
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
47
|
package Reflect; class Person{ public String getName() { return name; } public void setName(String name) { this .name = name; } public int getAge() {
return age; } public void setAge( int age) { this .age = age; } @Override public String toString(){ return "[" + this .name+ " " + this .age+ "]" ; } private String name; private int age; } class hello{ public static void
Class<?> demo= null ;
try { demo=Class.forName( "Reflect.Person" ); } catch (Exception e) {
e.printStackTrace(); } Person per= null ;
try { per=(Person)demo.newInstance(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } per.setName( "Rollen" );
per.setAge( 20 );
System.out.println(per); } } |
【运行结果】:
[Rollen 20]
但是注意一下,当我们把Person中的默认的无参构造函数取消的时候,比如自己定义只定义一个有参数的构造函数之后,会出现错误:
比如我定义了一个构造函数:
1
2
3
4
|
public Person(String name, int
this .age=age; this .name=name; } |
然后继续运行上面的程序,会出现:
java.lang.InstantiationException: Reflect.Person
at java.lang.Class.newInstance0(Class.java:340)
at java.lang.Class.newInstance(Class.java:308)
at Reflect.hello.main(hello.java:39)
Exception in thread "main" java.lang.NullPointerException
at Reflect.hello.main(hello.java:47)
所以大家以后再编写使用Class实例化其他类的对象的时候,一定要自己定义无参的构造函数
【案例】通过Class调用其他类中的构造函数(也可以通过这种方式通过Class创建其他类的对象)
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
package Reflect; import java.lang.reflect.Constructor; class Person{ public Person() { } public Person(String name){ this .name=name; } public Person( int
this .age=age; } public Person(String name, int age) { this .age=age; this .name=name; } public String getName() { return name; } public int getAge() {
return age; } @Override public String toString(){ return "[" + this .name+ " " + this .age+ "]" ; } private String name; private int age; } class hello{ public static void
Class<?> demo= null ;
try { demo=Class.forName( "Reflect.Person" ); } catch (Exception e) {
e.printStackTrace(); } Person per1= null ;
Person per2= null ;
Person per3= null ;
Person per4= null ;
//取得全部的构造函数 Constructor<?> cons[]=demo.getConstructors();
try { per1=(Person)cons[ 0 ].newInstance(); per2=(Person)cons[ 1 ].newInstance( "Rollen" ); per3=(Person)cons[ 2 ].newInstance( 20 ); per4=(Person)cons[ 3 ].newInstance( "Rollen" , 20 ); } catch (Exception e){
e.printStackTrace(); } System.out.println(per1); System.out.println(per2); System.out.println(per3); System.out.println(per4); } } |
【运行结果】:
[null 0]
[Rollen 0]
[null 20]
[Rollen 20]
【案例】
返回一个类实现的接口:
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
47
48
|
package Reflect; interface China{ public static final
"Rollen" ; public static int
20 ; public void sayChina();
public void sayHello(String name, int age); } class Person implements China{
public Person() { } public Person(String sex){ this .sex=sex; } public String getSex() { return sex; } public void setSex(String sex) { this .sex = sex; } @Override public void sayChina(){
System.out.println( "hello ,china" ); } @Override public void sayHello(String name, int age){ System.out.println(name+ " " +age); } private String sex; } class hello{ public static void
Class<?> demo= null ;
try { demo=Class.forName( "Reflect.Person" ); } catch (Exception e) {
e.printStackTrace(); } //保存所有的接口 Class<?> intes[]=demo.getInterfaces(); for ( int i = 0 ; i < intes.length; i++) { System.out.println( "实现的接口 " +intes[i].getName()); } } } |
【运行结果】:
实现的接口 Reflect.China
(注意,以下几个例子,都会用到这个例子的Person类,所以为节省篇幅,此处不再粘贴Person的代码部分,只粘贴主类hello的代码)
【案例】:取得其他类中的父类
1
2
3
4
5
6
7
8
9
10
11
12
13
|
class hello{ public static void
Class<?> demo= null ;
try { demo=Class.forName( "Reflect.Person" ); } catch (Exception e) {
e.printStackTrace(); } //取得父类 Class<?> temp=demo.getSuperclass(); System.out.println( "继承的父类为: " +temp.getName()); } } |
【运行结果】
继承的父类为: java.lang.Object
【案例】:获得其他类中的全部构造函数
这个例子需要在程序开头添加import java.lang.reflect.*;
然后将主类编写为:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
class hello{ public static void
Class<?> demo= null ;
try { demo=Class.forName( "Reflect.Person" ); } catch (Exception e) {
e.printStackTrace(); } Constructor<?>cons[]=demo.getConstructors();
for ( int i = 0 ; i < cons.length; i++) { System.out.println( "构造方法: " +cons[i]); } } } |
【运行结果】:
构造方法: public Reflect.Person()
构造方法: public Reflect.Person(java.lang.String)
但是细心的读者会发现,上面的构造函数没有public 或者private这一类的修饰符
下面这个例子我们就来获取修饰符
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
|
class hello{ public static void
Class<?> demo= null ;
try { demo=Class.forName( "Reflect.Person" ); } catch (Exception e) {
e.printStackTrace(); } Constructor<?>cons[]=demo.getConstructors();
for ( int i = 0 ; i < cons.length; i++) { Class<?> p[]=cons[i].getParameterTypes();
System.out.print( "构造方法: " ); int mo=cons[i].getModifiers();
System.out.print(Modifier.toString(mo)+ " " ); System.out.print(cons[i].getName()); System.out.print( "(" ); for ( int
0 ;j<p.length;++j){ System.out.print(p[j].getName()+ " arg" +i); if (j<p.length- 1 ){ System.out.print( "," ); } } System.out.println( "){}" ); } } } |
【运行结果】:
构造方法: public Reflect.Person(){}
构造方法: public Reflect.Person(java.lang.String arg1){}
有时候一个方法可能还有异常,呵呵。下面看看:
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
|
class hello{ public static void
Class<?> demo= null ;
try { demo=Class.forName( "Reflect.Person" ); } catch (Exception e) {
e.printStackTrace(); } Method method[]=demo.getMethods(); for ( int i= 0 ;i<method.length;++i){ Class<?> returnType=method[i].getReturnType(); Class<?> para[]=method[i].getParameterTypes(); int temp=method[i].getModifiers(); System.out.print(Modifier.toString(temp)+ " " ); System.out.print(returnType.getName()+ " " ); System.out.print(method[i].getName()+ " " ); System.out.print( "(" ); for ( int
0 ;j<para.length;++j){ System.out.print(para[j].getName()+ " " + "arg" +j); if (j<para.length- 1 ){ System.out.print( "," ); } } Class<?> exce[]=method[i].getExceptionTypes(); if (exce.length> 0 ){ System.out.print( ") throws " ); for ( int
0 ;k<exce.length;++k){ System.out.print(exce[k].getName()+ " " ); if (k<exce.length- 1 ){ System.out.print( "," ); } } } else { System.out.print( ")" ); } System.out.println(); } } } |
【运行结果】:
public java.lang.String getSex ()
public void setSex (java.lang.String arg0)
public void sayChina ()
public void sayHello (java.lang.String arg0,int arg1)
public final native void wait (long arg0) throws
java.lang.InterruptedException
public final void wait () throws java.lang.InterruptedException
public final void wait (long arg0,int arg1) throws
java.lang.InterruptedException
public boolean equals (java.lang.Object arg0)
public java.lang.String toString ()
public native int hashCode ()
public final native java.lang.Class getClass ()
public final native void notify ()
public final native void notifyAll ()
【案例】接下来让我们取得其他类的全部属性吧,最后我讲这些整理在一起,也就是通过class取得一个类的全部框架
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
|
class hello { public static void
Class<?> demo = null ;
try { demo = Class.forName( "Reflect.Person" ); } catch (Exception e) { e.printStackTrace(); } System.out.println( "===============本类属性========================" ); // 取得本类的全部属性 Field[] field = demo.getDeclaredFields();
for ( int i = 0 ; i < field.length; i++) { // 权限修饰符 int mo = field[i].getModifiers(); String priv = Modifier.toString(mo); // 属性类型 Class<?> type = field[i].getType(); System.out.println(priv + " " + type.getName() + " " + field[i].getName() + ";" ); } System.out.println( "===============实现的接口或者父类的属性========================" ); // 取得实现的接口或者父类的属性 Field[] filed1 = demo.getFields(); for ( int j = 0 ; j < filed1.length; j++) { // 权限修饰符 int mo = filed1[j].getModifiers(); String priv = Modifier.toString(mo); // 属性类型 Class<?> type = filed1[j].getType(); System.out.println(priv + " " + type.getName() + " " + filed1[j].getName() + ";" ); } } } |
【运行结果】:
===============本类属性========================
private java.lang.String sex;
===============实现的接口或者父类的属性========================
public static final java.lang.String name;
public static final int age;
【案例】其实还可以通过反射调用其他类中的方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
class hello { public static void
Class<?> demo = null ;
try { demo = Class.forName( "Reflect.Person" ); } catch (Exception e) { e.printStackTrace(); } try { //调用Person类中的sayChina方法 Method method=demo.getMethod( "sayChina" ); method.invoke(demo.newInstance()); //调用Person的sayHello方法 method=demo.getMethod( "sayHello" , String. class , int . class ); method.invoke(demo.newInstance(), "Rollen" , 20 ); } catch (Exception e) {
e.printStackTrace(); } } } |
【运行结果】:
hello ,china
Rollen 20
【案例】调用其他类的set和get方法
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
47
48
49
50
51
52
53
|
class hello { public static void
Class<?> demo = null ;
Object obj= null ;
try { demo = Class.forName( "Reflect.Person" ); } catch (Exception e) { e.printStackTrace(); } try { obj=demo.newInstance(); } catch (Exception e) {
e.printStackTrace(); } setter(obj, "Sex" , "男" ,String. class ); getter(obj, "Sex" );
} /** * @param obj * 操作的对象 * @param att * 操作的属性 * */ public static void
try { Method method = obj.getClass().getMethod( "get" + att); System.out.println(method.invoke(obj));
} catch (Exception e) { e.printStackTrace(); } } /** * @param obj * 操作的对象 * @param att * 操作的属性 * @param value * 设置的值 * @param type * 参数的属性 * */ public static void
Class<?> type) { try { Method method = obj.getClass().getMethod( "set" + att, type); method.invoke(obj, value); } catch (Exception e) { e.printStackTrace(); } } } // end class |
【运行结果】:
男
【案例】通过反射操作属性
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
class hello { public static void
throws Exception { Class<?> demo = null ;
Object obj = null ;
demo = Class.forName( "Reflect.Person" ); obj = demo.newInstance(); Field field = demo.getDeclaredField( "sex" ); field.setAccessible( true ); field.set(obj, "男" );
System.out.println(field.get(obj)); } } // end class |
【案例】通过反射取得并修改数组的信息:
1
2
3
4
5
6
7
8
9
10
11
12
|
import java.lang.reflect.*; class hello{ public static void
int [] temp={ 1 , 2 , 3 , 4 , 5 }; Class<?>demo=temp.getClass().getComponentType();
System.out.println( "数组类型: " +demo.getName()); System.out.println( "数组长度 " +Array.getLength(temp)); System.out.println( "数组的第一个元素: " +Array.get(temp, 0 )); Array.set(temp, 0 , 100 ); System.out.println( "修改之后数组第一个元素为: " +Array.get(temp, 0 )); } } |
【运行结果】:
数组类型: int
数组长度 5
数组的第一个元素: 1
修改之后数组第一个元素为: 100
【案例】通过反射修改数组大小
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
|
class hello{ public static void
int [] temp={ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 }; int [] newTemp=( int [])arrayInc(temp, 15 ); print(newTemp); System.out.println( "=====================" ); String[] atr={ "a" , "b" , "c" }; String[] str1=(String[])arrayInc(atr, 8 ); print(str1); } /** * 修改数组大小 * */ public static Object arrayInc(Object obj, int len){ Class<?>arr=obj.getClass().getComponentType();
Object newArr=Array.newInstance(arr, len);
int co=Array.getLength(obj);
System.arraycopy(obj, 0 , newArr, 0 , co); return newArr; } /** * 打印 * */ public static void
Class<?>c=obj.getClass(); if (!c.isArray()){
|