// 获取指定字段
Student student = new Student(); Class studentClass = Student.class; Field color = studentClass.getDeclaredField("name"); color.set(student,"xxx"); System.out.println(student.name); // xxx 获取构造方法 创建对象 public class Student extends Person{ private int id; public String name; protected int op; int t; public Student(int id, String name, int op, int t) { this.id = id; this.name = name; this.op = op; this.t = t; } @Override public String toString() { return "Student{" + "id=" + id + ", name='" + name + '\'' + ", op=" + op + ", t=" + t + '}'; } } public class ReflectTest { public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { Class studentClass = Student.class; Constructor constructor = studentClass.getConstructor(int.class, String.class, int.class, int.class); // 可能有重载必须指定参数类型 Student stu = (Student)constructor.newInstance(12, "Yes", 14, 13); // 创建对象 System.out.println(stu); // 操作私有的 必须先设置 字段名.setAccessible(true) Field id = studentClass.getDeclaredField("id"); id.setAccessible(true); int str = (Integer) id.get(stu); // 字段对象.get(字段属于类的真实对象) 得到这个真实对象的该字段值 System.out.println(str); } } // 结果 Student{id=12, name='Yes', op=14, t=13} 12 获取成员方法 public class Student { public void show(){ System.out.println("show time"); } public static void hello(int nu,int un){ System.out.println("==="+nu+un+"==="); } } public class ReflectTest { public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException { Class studentClass = Student.class; Student student = new Student(); Method show = studentClass.getDeclaredMethod("show", null); Method hello = studentClass.getDeclaredMethod("hello", int.class,int.class); // 方法执行 invoke(对象名,参数) show.invoke(student,null); //方法,没有参数 ,则写null hello.invoke(null,13,14); // 如果是静态方法,对象传入null } }