反射_复习

Java是面向对象的语言,一切皆对象,所以java认为 这些编译后的 class文件,这种事物也是一种对象,它也给抽象成了一种类,这个类就是Class

Class类: 能获取类的全部信息,包括它本身的方法,构造方法, 成员变量,成员函数。

class.getDeclaredXXX : 不区分访问修饰符的限制

如果是修饰符是private 还需要x.setAccessible(true);

 

示例代码:

通过反射对User进行操作:

package com.springmvc.inflect;

public class User {
    private String name;
    private String age;
    public User() {

    }

    public User(String name) {
        this.name = name;
    }

    public User(String name, String age) {
        this.name = name;
        this.age = age;
    }

    public String sayName(String name, String age) {
        this.name = name;
        this.age = age;
        return this.name;
    }
    public void sayName() {
        System.out.println(this.name);
    }
    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age='" + age + '\'' +
                '}';
    }
}

 

1. 实例化对象:

1.1 通过无参构造器实例化对象:

        Class userClass = Class.forName("com.springmvc.inflect.User");   // 获取这个类的class
        User user = (User)userClass.newInstance();
        System.out.println(user);

结果:

1.2 通过有参构造器实例化对象:

        Class userClass = Class.forName("com.springmvc.inflect.User");   // 获取这个类的class
        Constructor c = userClass.getDeclaredConstructor(String.class, String.class);
        User user = (User)c.newInstance("zhangsan", "12");
        System.out.println(user);

 

 

 结果:

 

 

 

 

 

2. 调用方法

2.1 调用无参方法

        Class userClass = Class.forName("com.springmvc.inflect.User");   // 获取这个类的class
        Constructor c = userClass.getDeclaredConstructor(String.class, String.class);
        User user = (User)c.newInstance("zhangsan", "12");

        Method m = userClass.getDeclaredMethod("sayName");
        m.invoke(user);

结果:

2.2调用有参方法

        Class userClass = Class.forName("com.springmvc.inflect.User");   // 获取这个类的class
        Constructor c = userClass.getDeclaredConstructor(String.class, String.class);
        User user = (User)c.newInstance("zhangsan", "12");
        
        // 形参数的Class
        Method m = userClass.getDeclaredMethod("sayName", String.class, String.class);
        // 实参 
        m.invoke(user,"lisi","13");
        System.out.println(user);

结果:

 

 

 

3. 设置成员变量

        Class userClass = Class.forName("com.springmvc.inflect.User");   // 获取这个类的class
        Constructor c = userClass.getDeclaredConstructor(String.class, String.class);
        User user = (User)c.newInstance("zhangsan", "12");

        Field f = userClass.getDeclaredField("age");
        f.setAccessible(true);
        f.set(user, "188");
        System.out.println(user);

结果:

 

posted @ 2020-11-01 22:14  圣金巫灵  阅读(69)  评论(0编辑  收藏  举报