利用反射机制 *使用无参构造器实例化 student * 使用有参构造器实例化student *
时间: 2023-07-30 14:10:48 浏览: 41
好的,以下是Java代码示例:
```java
// Student 类
public class Student {
private String name;
private int age;
// 无参构造器
public Student() {
this.name = "Unknown";
this.age = 0;
}
// 有参构造器
public Student(String name, int age) {
this.name = name;
this.age = age;
}
// getter 和 setter 省略
}
// 使用无参构造器实例化 student
Student student1 = null;
try {
Class<?> clazz = Class.forName("com.example.Student");
student1 = (Student) clazz.newInstance();
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
// 使用有参构造器实例化 student
Student student2 = null;
try {
Class<?> clazz = Class.forName("com.example.Student");
Constructor<?> constructor = clazz.getDeclaredConstructor(String.class, int.class);
constructor.setAccessible(true); // 如果构造器是私有的,需要设置可访问
student2 = (Student) constructor.newInstance("Tom", 18);
} catch (ClassNotFoundException | NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
```
其中,第一个例子使用了 `Class.newInstance()` 方法来实例化对象,这个方法会调用无参构造器来创建对象。第二个例子使用了 `Class.getDeclaredConstructor()` 方法来获取有参构造器的引用,并通过 `Constructor.newInstance()` 方法来实例化对象。需要注意的是,如果有参构造器是私有的,则需要设置可访问。