利用反射机制,使用无参构造器实例化Student 使用有参构造器实例化Student 实现Student练习代码
时间: 2024-03-01 08:54:56 浏览: 22
好的,下面是使用反射机制实例化Student类的练习代码:
```java
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
class Student {
private String name;
private int age;
public Student() {
this.name = "Tom";
this.age = 18;
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public void showInfo() {
System.out.println("Name: " + this.name);
System.out.println("Age: " + this.age);
}
}
public class ReflectDemo {
public static void main(String[] args) {
// 使用无参构造器实例化Student
try {
Class<?> clz = Class.forName("Student");
Constructor<?> constructor = clz.getDeclaredConstructor();
constructor.setAccessible(true);
Student student1 = (Student) constructor.newInstance();
student1.showInfo();
} catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException e) {
e.printStackTrace();
}
// 使用有参构造器实例化Student
try {
Class<?> clz = Class.forName("Student");
Constructor<?> constructor = clz.getDeclaredConstructor(String.class, int.class);
constructor.setAccessible(true);
Student student2 = (Student) constructor.newInstance("Jerry", 20);
student2.showInfo();
} catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException e) {
e.printStackTrace();
}
}
}
```
在上面的代码中,我们首先定义了一个Student类,包含了一个无参构造器和一个有参构造器,以及一个showInfo()方法用于输出学生的信息。然后在main()方法中,我们使用反射机制分别使用无参构造器和有参构造器来实例化Student类,并输出学生的信息。需要注意的是,在使用有参构造器时,我们需要指定构造器的参数类型和参数值。