- package reflex;
- public class Student{ 从外部调用要定义成public的
- public String name;
- public int age;
- public Student(String name,int age){
- 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;
- }
- public String toString(){
- return name+""+age;
- }
- }
复制代码- import java.lang.reflect.Constructor;
- import java.lang.reflect.Field;
- import reflex.Student; //由于Student类封装到了包里,这里必须引入Student.class文件
- public class ConstrucDemo1 {
- public static void main(String args[])throws Exception{
- //System.out.println(new Student().getClass()==new Student("wangwu",20).getClass());
- Student s=new Student("li",5); 由于重写了Student()方法,所以调用时必须代餐数调 用
- Class clazz=s.getClass();
- Constructor con=clazz.getConstructor(String.class,int.class);
- Student stu=(Student)con.newInstance("wangwu",34);
- Field f1=clazz.getDeclaredField("name");
- f1.setAccessible(true);
- System.out.println(f1.get(s));
- }
- }
复制代码 |