ZC_02_获取Constructor
1、
package reflectionZ; import java.lang.reflect.Constructor; import java.lang.reflect.Type; public class Tzz02 { public static void main(String[] args) throws Exception { // getConstructors() / getConstructor(...) Class<?> clazz1 = Class.forName("reflectionZ.Cat"); // 1、使用的是 默认的 构造函数 Object obj01 = clazz1.newInstance(); // 2、通过Class对象来得到构造函数 Constructor<?> c1 = clazz1.getConstructor(Class.forName("java.lang.String"), int.class); Object obj0201 = c1.newInstance("小猫", 6); // 强转 Constructor<?> c2 = clazz1.getConstructor(String[].class); String[] foods = {"鱼", "老鼠"}; Object obj0202 = (Cat)c2.newInstance((Object)foods); // 对象数组foods会被打散 if (obj01.getClass() == clazz1) System.out.println("obj01.getClass() == clazz1"); else System.out.println("obj01.getClass() != clazz1"); if (obj0201.getClass() == clazz1) System.out.println("obj01.getClass() == clazz1"); else System.out.println("obj01.getClass() != clazz1"); if (obj0202.getClass() == clazz1) System.out.println("obj01.getClass() == clazz1"); else System.out.println("obj01.getClass() != clazz1"); // *** *** *** System.out.println(); int iIdx = 0; Constructor<?>[] constructors = clazz1.getConstructors(); for (Constructor<?> constructor :constructors) { Type[] types = constructor.getGenericParameterTypes(); if (types.length == 0) System.out.println("["+iIdx+"] ==> 无参构造函数"); else { System.out.println("["+iIdx+"] ==> "+types.length+"个参数的 构造函数,参数的类型分别为:"); for (Type type : types) { System.out.println(type); } } System.out.println(); iIdx ++; } } } class Cat { public Cat() {} public Cat(String _strName, int _iAge) { System.out.println("Cat --> _strName : "+_strName+" , _iAge : "+_iAge); } public Cat(String[] _foods) { if (_foods == null) System.out.println("Cat --> _foods is null ."); else { for (int i=0; i<_foods.length; i++) System.out.println("Cat --> _foods["+i+"] : "+_foods[i]); } } }
2、
控制台输出:
Cat --> _strName : 小猫 , _iAge : 6
Cat --> _foods[0] : 鱼
Cat --> _foods[1] : 老鼠
obj01.getClass() == clazz1
obj01.getClass() == clazz1
obj01.getClass() == clazz1
[0] ==> 无参构造函数
[1] ==> 2个参数的 构造函数,参数的类型分别为:
class java.lang.String
int
[2] ==> 1个参数的 构造函数,参数的类型分别为:
class [Ljava.lang.String;
3、