Home >Java >javaTutorial >What is Java reflection? Detailed introduction to Java reflection mechanism

What is Java reflection? Detailed introduction to Java reflection mechanism

不言
不言Original
2018-09-19 14:30:162043browse

This article brings you what is Java reflection? The detailed introduction of Java reflection mechanism has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. Concept

Java reflection (Reflection) means that when a Java program is running, it can load a class whose name is known only, obtain the complete construction method of the class, and instantiate the object, giving Set values ​​for object properties or call object methods. This function of dynamically obtaining class information and dynamically calling object methods at runtime is called Java's reflection mechanism.

2. Class class

The Class class inherits from the Object class and is the entrance to the Java reflection mechanism. It encapsulates the runtime information of a class or interface and can be obtained by calling the method of the Class class. these messages. How to understand this Class class? If an ordinary class is a collection of all object methods and attributes, then this Class class can be understood as a collection of all ordinary classes.

The following are several methods of obtaining the Class class:

public class TestClass {
    public static void main(String[] args) throws ClassNotFoundException {
        // 1、 Class.forName();
        Class<?> aClass0 = Class.forName("java.lang.Object");
        // 2、类名.Class
        Class<Integer> aClass1 = Integer.class;
        // 3、包装类.TYPE —— 返回基本类型的 Class 引用,基本类型在虚拟机运行时就已经加载了它的Class
        Class<Integer> aClass2 = Integer.TYPE;
        // 4、对象名.getClass()
        String str = "Hello, World";
        Class<? extends String> aClass3 = str.getClass();
        // 5、Class类.getSuperClass() —— 获得父类的 Class 对象
        Class<?> aClass4 = aClass3.getSuperclass();

        System.out.println(aClass0.getName());
        System.out.println(aClass1.getName());
        System.out.println(aClass2.getName());
        System.out.println(aClass3.getName());
        System.out.println(aClass4.getName());
    }
}

3. Obtaining class information

In order to test the reflection mechanism of Java, I created a new pair of parent and child classes. It covers four encapsulation properties to test the acquisition of multiple types of information as much as possible:

Vehicle.java

vpublic class Vehicle {
    private String color;
    protected Integer seat;
    int year;
    public Date createdOn;
    private String getColor() {
        return color;
    }
    protected Integer getSeat() {
        return seat;
    }
    int getYear() {
        return year;
    }
    public Date getCreatedOn() {
        return createdOn;
    }
}

Car.java

public class Car extends Vehicle {
    private String brand;
    protected Integer a;
    int b;
    public Date updatedOn;
    public Car(){}
    private Car(String brand, Integer a, int b, Date updatedOn) {
        this.brand = brand;
        this.a = a;
        this.b = b;
        this.updatedOn = updatedOn;
    }
    private String getBrand() {
        return brand;
    }
    protected Integer getA() {
        return a;
    }
    int getB() {
        return b;
    }
    public Date getUpdatedOn() {
        return updatedOn;
    }
}

1. Obtaining methods

Class classes mainly obtain methods in the following two ways:

Method[] getMethods() returns all accessible public methods of the class or interface (Including inherited public methods).

Method[] getDeclaredMethods() Returns all methods of this class or interface (excluding inherited methods).

public class TestMethod {
    public static void main(String[] args) {
        Class<Car> carClass = Car.class;
        Method[] methods = carClass.getMethods();
        Method[] declaredMethods = carClass.getDeclaredMethods();

        for (Method method : methods) {
        //for (Method method : declaredMethods) {
            System.out.println("方法名:" + method.getName());
            System.out.println("该方法所在的类或接口:" + method.getDeclaringClass());
            System.out.println("该方法的参数列表:" + method.getParameterTypes());
            System.out.println("该方法的异常列表:" + method.getExceptionTypes());
            System.out.println("该方法的返回值类型:" + method.getReturnType());
        }
    }
}

2. Obtain attributes

Class class mainly obtains attributes through the following two methods:

Field[] getFields(): storage All accessible public properties of this class or interface (including inherited public properties).

Field[] getDeclaredFields(): Stores all properties of the class or interface (excluding inherited properties).

public class TestField {
    public static void main(String[] args) {
        Class<Car> carClass = Car.class;
        Field[] fields = carClass.getFields();
        Field[] declaredFields = carClass.getDeclaredFields();
        //for (Field field : fields) {
        for (Field field : declaredFields) {
            System.out.println("属性名称是:" + field.getName());
            System.out.println("该属性所在的类或接口是:" + field.getDeclaringClass());
            System.out.println("该属性的类型是:" + field.getType());
            // field.getModifiers() 以整数形式返回由此 Field 对象表示的属性的 Java 访问权限修饰符
            System.out.println("该属性的修饰符是:" + Modifier.toString(field.getModifiers()));
        }
    }
}

3. Obtain the constructor

The Class class mainly obtains the constructor method in the following two ways:

Constructor6b3d0130bba23ae47fe2b8e8cddf0195[ ] getConstructors(): Returns all the public constructors of the class or interface

Constructor6b3d0130bba23ae47fe2b8e8cddf0195[] getDeclaredConstructors(): Returns all the constructors of the class or interface

public class TestConstructor {
    public static void main(String[] args) throws NoSuchMethodException {
        Class<Car> carClass = Car.class;
        Constructor<?>[] constructors = carClass.getConstructors();
        Constructor<?>[] declaredConstructors = carClass.getDeclaredConstructors();
        Constructor<Car> carConstructor = carClass.getDeclaredConstructor(String.class, Integer.class, Integer.TYPE, Date.class);
        //for (Constructor constructor : declaredConstructors) {
        for (Constructor constructor : constructors) {
            System.out.println("该构造器的名称是:" + constructor.getName());
            System.out.println("该构造器所在的类或接口是:" + constructor.getDeclaringClass());
            //返回构造方法的参数类型
            constructor.getParameterTypes();
        }
    }
}

four , Dynamic call

So far, we have obtained the detailed information of the corresponding class attributes, methods and constructors through the methods of the Class class. Next we will use this information to dynamically create objects, modify properties and dynamically call methods.

public class Test {
    public static void main(String[] args) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
        Class<Car> carClass = Car.class;
        // 1、实例化对象
        // 调用 Class 类的newInstance();要求对应类必须有无参构造函数,相当于 Car car = new Car()
        Car car = carClass.newInstance();
        // 调用构造器的newInstance(Object ... initargs);
        Constructor<Car> declaredConstructor = carClass.getDeclaredConstructor(String.class, Integer.class, Integer.TYPE, Date.class);
        // 取消访问权限控制,即使是 private 权限也可以访问
        declaredConstructor.setAccessible(true);
        Car car1 = declaredConstructor.newInstance("brand", 21, 21, new Date());
        System.out.println(car1.getUpdatedOn());

        // 2、修改属性
        Field brand = carClass.getDeclaredField("brand");
        brand.setAccessible(true);
        System.out.println("取消访问权限控制后的值:" + brand.get(car1));
        brand.set(car1, "dnarb");
        System.out.println("修改属性后的值是:" + brand.get(car1));

        // 3、调用方法
        Method getBrand = carClass.getDeclaredMethod("getBrand");
        getBrand.setAccessible(true);
        System.out.println("调用反射方法得到的值是:" + getBrand.invoke(car1));
    }
}

The above is the detailed content of What is Java reflection? Detailed introduction to Java reflection mechanism. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn