一、说明
Java Reflection是被视为动态语言的关键,反射机制允许程序在执行期间借助于Reflection API取得任何类的内部信息,并能直接操作任意对象的内部属性及方法。
1.Java反射机制提供的功能
- 在运行时判断任意一个对象所属的类
- 在运行时构造任意一个类的对象
- 在运行时判断任意一个类所具有的成员变量和方法
- 在运行时调用任意一个对象的成员变量和方法
- 生成动态代理 2.反射相关的API
- java.lang.Class:代表一个类
- java.lang.reflect.Method:代表类的方法
- java.lang.reflect.Field:代表类的成员变量
- java.lang.reflect.Constructor:代表类的构造方法
二、例子
ts对象封装类,包含构造方法(有参、无参)。show(),display()方法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
31public class ts{
public int no;//设置为公有,后面用到,与私有调用的区别
private String name;
public ts(int no, String name) {
super();
this.no = no;
this.name = name;
}
public ts() {}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void show(){
System.out.print("1231323");
}
public void display(String sex){
System.out.println(sex);
}
}
测试类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
38public class Test{
//普通面向对象调用
public void test(){
ts t=new ts();//实例化
t.setNo(1);
t.setName("zx");
t.show();
t.display("男");
}
//反射调用
public void test1(){
Class<ts> clazz=ts.class;//clazz就代表ts
//1.创建clazz运行时的ts对象
ts t=clazz.newInstance();
//2.通过反射原理调用运行时类的指定的属性
Field f1=clazz.getField(no);
f1.set(t,1);
//3.调用私有属性
Field f2=clazz.getDeclareField("name");
f2.setAccessible(true);
f2.set(t,"zx");
//4.通过反射原理调用运行时类的指定的方法
//getMethod的第二个参数是调用方法的参数类,invoke时写具体参数值,有多少个就写duo
Method m1=clazz.getMethod("show");
m1.invoke(t);
Method m2=clazz.getMethod("display",String.class);
m2.invoke(t,"男");
}
}