Java SE练习 - 反射获取对象构造方法、成员变量、成员方法

时间:2022-12-12 11:56:47

前言:反射使用回顾

一、获取字节码文件对象的三种方式,推荐使用第三种方式

//获取字节码文件对象的三种方式
        //方式一
        Class c1 = Student.class;
        //方式二
        Student stu = new Student();
        Class c2 = stu.getClass();
        //方式三
        Class c3 = Class.forName("cn.itcast.javaeevideoday02.Student");

二、获取无参构造

//获取对象无参构造
        Constructor constructor = c3.getConstructor();
        Object student = constructor.newInstance();
        System.out.println(student);

三、获取有参构造

//获取有参构造
        Constructor constructor2 = c3.getConstructor(String.class,int.class,String.class);
        Object student2 = constructor2.newInstance("张三",20,"男");
        System.out.println(student2);

四、快捷方式获取对象实例
前提:对象有空参构造,并且权限为public

//快捷方式获取对象实例
        Object student = c3.newInstance();
        System.out.println(student);

五、获取对象成员变量,并赋值和获取值

Object student = c3.newInstance();

        //给成员变量赋值
        Field field = c3.getField("name");
        field.set(student, "张三");
        System.out.println(student);
        //获取成员变量值
        Object object = field.get(student);
        System.out.println(object);

六、获取成员方法
get/set方法示例

Object student = c3.newInstance();

        //有参数set
        Method method = c3.getMethod("setName",String.class);
        method.invoke(student, "张三");
        System.out.println(student);

        //无参数get
        Method method2 = c3.getMethod("getName");
        Object object = method2.invoke(student);
        System.out.println(object);