// 需求说明
// 定义Student类,包含:姓名和年龄等属性,有参和无参构造方法,输出所有信息的方法
// 使用多种方法生成一个Student类的Class对象
// 使用Class类获取Student类的结构信息并输出
// 通过有参(无参)构造方法动态创建Student类的对象
// 使用反射修改和查询Student类的姓名属性
// 使用反射动态执行Student类输出所有信息的方法
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Test3 {
public static void main(String[] args) throws ClassNotFoundException,
NoSuchMethodException, SecurityException, InstantiationException,
IllegalAccessException, IllegalArgumentException,
InvocationTargetException, NoSuchFieldException {
// 需求说明
// 定义Student类,包含:姓名和年龄等属性,有参和无参构造方法,输出所有信息的方法
// 使用多种方法生成一个Student类的Class对象
// 使用Class类获取Student类的结构信息并输出
// 通过有参(无参)构造方法动态创建Student类的对象
// 使用反射修改和查询Student类的姓名属性
// 使用反射动态执行Student类输出所有信息的方法
// 使用多种方法生成一个Student类的Class对象
// 方法1
Student stuTemp = new Student();
Class stu2 = stuTemp.getClass();
// 方法2
Class stu1 = Class.forName("cn.zhangwendi.day7.Student");
// 方法3
Class stu3 = Student.class;
// 使用Class类获取Student类的结构信息并输出
// 通过有参(无参)构造方法动态创建Student类的对象
Constructor con = stu1.getConstructor();// 无参
Constructor con2 = stu1.getConstructor(String.class, int.class);// 有参
Student student = (Student) con.newInstance();
Student student2 = (Student) con2.newInstance("zhangsan", 20);
// 使用反射修改和查询Student类的姓名属性
Field field = stu1.getDeclaredField("name");// 通过姓名属性修改姓名属性
field.setAccessible(true);
field.set(student, "张海迪");
System.out.println(student);
Method meth = stu1.getDeclaredMethod("setName", String.class);// 通过set方法修改姓名属性
meth.invoke(student, "张大仙");
System.out.println(student);
// 使用反射动态执行Student类输出所有信息的方法
Method meth2 = stu1.getDeclaredMethod("toString");
System.out.println(student.toString());
}
}
public class Student {
String name;
private int age;
public Student() {
super();
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}
}