Java笔记 -反射

通过 Class、Constructor、Field、Method 这些类来创建对象

机制

  • 利用反射可以无视修饰符获取类里面所有的属性和方法
  • 先获取配置文件中的信息,动态获取信息并创建对象和调用方法

好处/弊端

  • 使用反射的方式写的代码灵活
  • 使用反射的方式写的代码复杂、繁琐

Class对象

获取Class类的对象

方式1

Class 类中的静态方法 forName("全类名")

Class.forName("");

方式2

通过 class 属性获取

类名.class;

方式3

利用对象的 getClass() 方法

对象.getClass();

Constructor对象

获取Constructor对象

  • Class.getConstructors()
  • Class.getDeclaredConstructors() // 可以吧私有的构造方法获取到
  • Class.getConstructor() // 参数要和构造方法中参数一致
  • Class.getDrclaedConstructor()

利用Constructor创建对象

  • Constructor.newInstance();
  • Class.newInstance();
  • private 修饰的构造方法不可直接使用,需要临时取消访问检查: constructor.seAccessible(true);
public class Student {
    private String name;
    private Integer age;

    private Student(String name) {
        this.name = name;
    }

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

    public Student() {
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

public class Test {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Class<?> sClass = Class.forName("com.xlrong.test2.Student");
        Constructor[] constructors = sClass.getConstructors();

        for (Constructor constructor : constructors) {
            System.out.println(constructor);
        }
        System.out.println("---------------------------");

        Constructor<?>[] declaredConstructors = sClass.getDeclaredConstructors();
        for (Constructor<?> declaredConstructor : declaredConstructors) {
            System.out.println(declaredConstructor);
        }
        System.out.println("---------------------------");

        Constructor constructor = sClass.getConstructor();

        Student o1 = (Student) constructor.newInstance();
        o1.setName("Test");

        System.out.println(o1);

        Constructor constructor2 = sClass.getConstructor(String.class, Integer.class);
        Student o2 = (Student) constructor2.newInstance("Test2", 3);
        System.out.println(o2);

        Constructor declaredConstructor = sClass.getDeclaredConstructor(String.class);
        declaredConstructor.setAccessible(true);
        Student o3 = (Student) declaredConstructor.newInstance("Test3");
        System.out.println(o3);
    }
}

Field对象

获取Field对象

  • Class.getFields()
  • Class.getDeclaredFields()
  • Class.getField()
  • Class.getDeclaredField()

获取成员变量并使用

  • get(Object, Object);
  • set(Object);
public class Student {
    private String name;
    private Integer age;

    private Student(String name) {
        this.name = name;
    }

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

    public Student() {
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

public class FieldTest {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchFieldException {
        Class aClass = Class.forName("com.xlrong.test2.Student");

        Field field = aClass.getDeclaredField("name");

        field.setAccessible(true);
        Student student = (Student) aClass.newInstance();
        System.out.println(student);

        field.set(student, "Test");
        System.out.println(student);

        Object o = field.get(student);
        System.out.println(o);
    }
}

Method对象

获取Method对象

  • Class.getMethods()
  • Class.getDeclaredMethods()
  • Class.getMethod()
  • Class.getDeclaredMethod()
public class Student {
    private String name;
    private Integer age;

    private Student(String name) {
        this.name = name;
    }

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

    public Student() {
    }

    private String show(String str) {
        System.out.println("show方法被调用: " + str);
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

public class MethodTest {
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        Class aClass = Class.forName("com.xlrong.test2.Student");

        Student stu = (Student) aClass.newInstance();

        Method show = aClass.getDeclaredMethod("show", String.class);

        show.setAccessible(true);
        Object o = show.invoke(stu, "测试");
        System.out.println(o);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值