想生成對象的實體,在反射動態機制中有兩種方法,一個針對無變量的構造方法,一個針對帶參數的構造方法,,如果想調用無參數的構造函數直接調用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
客戶虐我千百遍,我待客戶如初戀!