关于JAVA的反射具有数组参数的类的方法

遇到一个关于反射具有数组参数的类问题,通过查阅JDK文档,终于解决了,兴奋~~~

Class<T>类、Constructor<T>类,需要好好理解其作用。

某个类可以通过其    bject.getConstructor    获取该类的构造方法,再用(Constructor)c.newInstance([参数数组]),来完成一个类的实例化。

说明:

newInstance的参数必需是Object[],这个数组是不定长的。

例一:

非数组参数

1
2
3
4
5
6
public Role(String name,String sex,int age){}
			Constructor&lt; ? extends Role&gt; constructor = inCmdClass.getConstructor(String.class,String.class,Integer.class);
			Role role = constructor.newInstance(new Object[]{”wangming”,”male”,23});
role.getName();//wangming
role.getSex();//male
role.getAge();//23

例二:

数组参数

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
public class TestReflect {
 
	public TestReflect(String name,String sex,String[] books){
		System.out.println(name + &quot;:&quot; + sex +&quot;:&quot; +books.length);
	}
 
	public TestReflect(String[] books){
		System.out.println(books.length);
	}
 
	/**
	 * @param args
	 * @throws NoSuchMethodException 
	 * @throws SecurityException 
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 * @throws InstantiationException 
	 * @throws IllegalArgumentException 
	 */
	public static void main(String[] args) throws SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException {
		System.out.println(&quot;~~~~~~~~~~~c1~~~~~~~~~~~~&quot;);
		Constructor&lt; ? extends TestReflect&gt; c1 = TestReflectOne.class.getConstructor(String.class,String.class,String[].class);
		c1.newInstance(&quot;wang&quot;,&quot;male&quot;,args);
		System.out.println(&quot;~~~~~~~~~~~c2~~~~~~~~~~~~&quot;);
		Constructor&lt; ? extends TestReflect&gt; c2 = TestReflectOne.class.getConstructor(String.class,String.class,String[].class);
		c2.newInstance(new Object[]{&quot;wang&quot;,&quot;male&quot;,args});
		System.out.println(&quot;~~~~~~~~~~~c3~~~~~~~~~~~~&quot;);
		Constructor&lt; ? extends TestReflect&gt; c3 = TestReflectOne.class.getConstructor(new Class[]{String.class,String.class,String[].class});
		c3.newInstance(new Object[]{&quot;wang&quot;,&quot;male&quot;,args});
		System.out.println(&quot;~~~~~~~~~~~c4~~~~~~~~~~~~&quot;);
		Constructor&lt; ? extends TestReflect&gt; c4 = TestReflectOne.class.getConstructor(String[].class);
		c4.newInstance(new Object[]{args});//这里必需要这样写
 
	}
 
}
 
 
public class TestReflectOne extends TestReflect {
 
	public TestReflectOne(String name, String sex, String[] books) {
		super(name, sex, books);
		System.out.println(&quot;TestReflectOne&quot;);
	}
 
	public TestReflectOne(String[] books) {
		super(books);
		System.out.println(&quot;TestReflectOne&quot;);
	}
 
}