51,408
社区成员
发帖
与我相关
我的任务
分享
import java.lang.reflect.*;
public class Main_01 {
public static void main(String[] args) {
Example_01 example = new Example_01("10", "20", "30");
Class<? extends Example_01> exampleC = example.getClass();
// 获的所有构造函数
Constructor[] declaredConstructors = exampleC.getDeclaredConstructors();
for (int i = 0; i < declaredConstructors.length; i++) {
// 遍历构造方法
Constructor<?> constructor = declaredConstructors[i];
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]);
}
// 获得所有可能抛出的异常信息类型
System.out.println("该构造方法可能抛出的异常类型为:");
Class[] exceptionTypes = constructor.getExceptionTypes();
for (int j = 0; j < exceptionTypes.length; j++) {
System.out.println(" " + exceptionTypes[j]);
}
Example_01 example2 = null;
while (example2 == null) {
// 如果该成员变量的访问权限为private,则抛出异常,即不允许访问
try {
if (i == 2) {
// 通过执行默认没有参数的构造方法创建对象
example2 = (Example_01)constructor.newInstance();
}else if (i == 1) {
// 通过执行2个参数的构造方法创建对象
example2 = (Example_01)constructor.newInstance("2", 6);
}else {
// 通过执行多个参数的构造方法创建对象
Object[] parameters = new Object[] {new String[] {"222", "666", "888"}};
example2 = (Example_01)constructor.newInstance(parameters);
}
} catch (Exception e) {
System.out.println("在创建对象时抛出异常,下面执行setAccessible()方法");
constructor.setAccessible(true); // 设置为允许访问
}
}
if (example2 != null) {
example.print();
System.out.println();
}
}
}
中以下两处的目的?
Example_01 example = new Example_01("10", "20", "30");
Example_01 example2 = null;
new出来不是为了下面
if (example2 != null) {
example.print();
System.out.println();
}
这里能调用example.print()
同样Example_01 example2 = null;也只是为了while循环后能拿到example2判断他!= null
没啥别的目的啊?