想生成对象的实体,在反射动态机制中有两种方法,一个针对无变量的构造方法,一个针对带参数的构造方法,,如果想调用无参数的构造函数直接调用Class类中的newInstance(),而如果想调用有参数的构造函数,则需要调用Constructor类中newInstance()方法,首先准备一个Class[]作为Constructor的参数类型。然后调用该Class对象的getConstructor()方法获得一个专属的Constructor的对象,最后再准备一个Object[]作为Constructor对象昂的newInstance()方法的实参。
在这里需要说明的是 只有两个类拥有newInstance()方法,分别是Class类和Constructor类,Class类中的newInstance()方法是不带参数的,而Constructro类中的newInstance()方法是带参数的需要提供必要的参数。
下面提供的代码是构造Customer2类的三个构造函数
1
import java.lang.reflect.Constructor;
2
import java.lang.reflect.InvocationTargetException;
3
4
/** *//**
5
* 在反射Reflection机制中,想生成一个类的实例有两种方法 一个是针对无参数的构造函数 ,另一个是针对有参数的构造函数
6
*
7
*/
8
public class ReflecTest3
{
9
10
/** *//**
11
* 反射的动态性质之一: 运行期动态生成Instance
12
*
13
* @throws IllegalAccessException
14
* @throws InstantiationException
15
* @throws NoSuchMethodException
16
* @throws InvocationTargetException
17
* @throws SecurityException
18
* @throws IllegalArgumentException
19
*/
20
public static void main(String[] args) throws InstantiationException, IllegalAccessException, IllegalArgumentException, SecurityException, InvocationTargetException, NoSuchMethodException
{
21
Customer2 customer = new Customer2();
22
Class cls=customer.getClass();
23
// 获得Class所代表的对象的所有类型的构造函数Constructor的数组
24
Constructor ctor[]=cls.getDeclaredConstructors();
25
for(int i=0;i<ctor.length;i++)
{
26
// 获得对应的构造函数参数列表的Class类型的数组
27
Class cx[]=ctor[i].getParameterTypes();
28
if(cx.length==0)
{
29
Object obj=cls.newInstance();
30
System.out.println(obj);
31
}else if(cx.length==2)
{
32
Customer2 obj=(Customer2)cls.getConstructor(cx).newInstance(new Object[]
{new Long(123),"hejianjie"});
33
System.out.println(obj);
34
}else if(cx.length==3)
{
35
Customer2 obj=(Customer2)cls.getConstructor(cx).newInstance(new Object[]
{new Long(133),"China-Boy",new Integer(21)});
36
System.out.println(obj);
37
}
38
}
39
}
40
}
41
42
class Customer2
{
43
44
private Long id;
45
46
private String name;
47
48
private int age;
49
50
/** *//**
51
* 无参数的构造函数
52
*
53
*/
54
public Customer2()
{
55
56
}
57
58
/** *//**
59
* public修饰的有参数的构造函数,3个参数
60
*
61
* @param id
62
* @param name
63
* @param age
64
*/
65
public Customer2(Long id, String name, int age)
{
66
this.id = id;
67
this.name = name;
68
this.age = age;
69
}
70
71
/** *//**
72
* public修饰的构造函数,2个参数
73
*
74
* @param id
75
* @param name
76
*/
77
public Customer2(Long id, String name)
{
78
this.id = id;
79
this.name = name;
80
this.age = age;
81
}
82
83
public int getAge()
{
84
return age;
85
}
86
87
public void setAge(int age)
{
88
this.age = age;
89
}
90
91
public Long getId()
{
92
return id;
93
}
94
95
public void setId(Long id)
{
96
this.id = id;
97
}
98
99
public String getName()
{
100
return name;
101
}
102
103
public void setName(String name)
{
104
this.name = name;
105
}
106
107
public String toString()
{
108
return ("id==" + this.getId() + " Name==" + this.getName() + " Age:" + this.getAge());
109
}
110
111
}
112
客户虐我千百遍,我待客户如初恋!