1.定义一个类
public class TestItem {
String s;
int i;
int i2;
int i3;
private TestItem(){
}
protected TestItem(String s, int i) {
this.s = s;
this.i = i;
}
public TestItem(String...strings ) {
if (0 < strings.length) {
i = Integer.valueOf(strings[0]);
}
if (1 < strings.length) {
i2 = Integer.valueOf(strings[1]);
}
if (2 < strings.length) {
i3 = Integer.valueOf(strings[2]);
}
}
public void print() {
System.out.println("s = " + s);
System.out.println("i = " + i);
System.out.println("i2 = " + i2);
System.out.println("i3 = " + i3);
}
}
2.测试类
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class TestConstructor {
public static void main(String[] args) {
TestItem testIt = new TestItem("10", "20", "30");
Class<? extends TestItem> example = testIt.getClass();
Constructor[] declaredConstructors = example.getDeclaredConstructors();
System.out.println("构造方法数量为:" + declaredConstructors.length);
for (int i = 0; i < declaredConstructors.length; i++) {
System.out.println("第 " + i + "次循环");
Constructor<?> constructor = declaredConstructors[i];
// 仅构造方法的修饰符为public时,输出才为true,否则为false
System.out.println("查看是否允许带有可变数量的参数:" + constructor.isVarArgs());
System.out.println("该构造方法的入口参数类型依次为:");
Class[] parameterTypes = constructor.getParameterTypes();
for (int j = 0; j < parameterTypes.length; j++) {
System.out.println(" " + parameterTypes[j]);
}
// 此处执行为空,异常数量循环三次一直为0?
System.out.println("该构造方法可能抛出的异常类型为:");
Class[] exceptionTypes = constructor.getExceptionTypes();
for (int j = 0; j < exceptionTypes.length; j++) {
System.out.println(" " + exceptionTypes[j]);
}
System.out.println("异常数量为:" + exceptionTypes.length);
TestItem testExample = null;
while (testExample == null) {
try {
if (i == 2) {//第2次循环,使用无参构造方法初始化类的对象//此时调用private TestItem()
testExample = (TestItem) constructor.newInstance();
} else if (i == 1) {//第1次循环,使用两个参数的构造方法初始化对象//此时调用protected TestItem(String s, int i)
testExample = (TestItem) constructor.newInstance("7", 5);
} else {// 第0次循环及其他次循环//此时调用public TestItem(String...strings )
Object[] parameters = new Object[] {
new String[] {"100", "200", "300"}
};
testExample = (TestItem) constructor.newInstance(parameters);
// testExample = (TestItem) constructor.newInstance("100", "200", "300");
}
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
System.out.println("在创建对象时抛出异常,下面执行setAccessible()方法");
constructor.setAccessible(true);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
if (testExample != null) {
System.out.println("执行TestItem类的print方法: ");
testExample.print();
System.out.println("----------");
}
}
}
}
}