import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class FieldDemo {
public static void main(String[] args) throws Exception {
Class<Student> stuClass = Student.class;
// newInstance()可以创建实例对象
Student student = stuClass.newInstance();
// getDeclaredField按指定名字获取Field
Field field1 = stuClass.getDeclaredField("id");
// 访问类自己定义的私有属性
field1.setAccessible(true);
field1.set(student, 12);
System.out.println(student.getId());
// getDeclaredMethod按指定名字获取Method
Method privateStudyMethod = stuClass.getDeclaredMethod("setAge",int.class);
// 调用的方法是public的,就不需要进行设置
privateStudyMethod.setAccessible(true);
privateStudyMethod.invoke(student, 24);
System.out.println(student.age);
Constructor<?> constructor = stuClass.getDeclaredConstructor(int.class,String.class,String.class,int.class);
// 不是public修饰,就需要进行设置
constructor.setAccessible(true);
Student student1 = (Student) constructor.newInstance(11,"张三", "男",24);
System.out.println("该学生的姓名是" + student1.getName());
}
}