Home  >  Article  >  Java  >  What is the meaning and role of reflection in Java?

What is the meaning and role of reflection in Java?

WBOY
WBOYforward
2023-04-21 15:16:081442browse

1. Overview of Reflection

Reflection (reflection) is the key to being regarded as a dynamic language. The reflection mechanism allows the program to obtain the internal information of any class through the Reflection API during execution, and can directly operate any object. internal properties and methods. After the class is loaded, a Class type object is generated in the method area of ​​the heap memory (a class has only one Class object). This object contains the complete structural information of the class. We can see the structure of the class through this object. This object is like a mirror. We can see the structure of the class through this mirror, so we vividly call it reflection.

2. Commonly used api

java.lang.Class: represents a class

java.lang.reflect.Method : Represents the method of the class

java.lang.reflect.Field: Represents the member variable of the class

java.lang.reflect.Constructor: Constructor representing the class

static Class forName(String name) Returns the Class object of the specified class name name

Object newInstance() Call None Parameter constructor, return an instance of the Class object

getName() Return the name of the entity (class, interface, array class, basic type or void) represented by this Class object

Class getSuperClass() Returns the Class object of the parent class of the current Class object

Class [] getInterfaces() Gets the interface of the current Class object

ClassLoader getClassLoader() Returns the class loader of this class

Class getSuperclass() Returns the Class that represents the super class of the entity represented by this Class

Constructor[] getConstructors() Returns an array containing certain Constructor objects

Field[] getDeclaredFields() Returns an array of Field objects ArrayMethod

getMethod(String name,Class … paramTypes) Returns a Method object, the formal parameter type of this object is paramType

Example:

public class Person {
    private String name;
    private int age;
    public Person() {
        System.out.println("Person类被初始化了。。。。。^_^");
    }
    public Person(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;
    }
    @Override
    public String toString() {
        return "Person{" +
            "name='" + name + '\'' +
            ", age=" + age +
            '}';
    }
}

Reflection

public class ClassDemo {
    public static void main(String[] args) throws
        Exception {
        // 1. 创建Class对象
        //Class<Person> clazz = (Class<Person>)
        Class.forName("Person");
        Class<?> clazz =Class.forName("Person");
            // 2. 通过Class对象调用其方法
            // 2.1. 通过反射来实例化对象
            //Person person = clazz.newInstance();
            Object o = clazz.newInstance(); // 此名就相当于
        Person p = new Person()
            // 2.2. 获取类的完整类名称(包名+类名)
            String name = clazz.getName();
        System.out.println(name);
        // 2.3. 获取类的简单名称,就是类的名称,不含包名
        System.out.println(clazz.getSimpleName());
        // 2.4. 获取构造器
        Constructor<?>[] constructors =
            clazz.getConstructors();
        for (Constructor<?> constructor :
             constructors) {
            System.out.println(constructor.getName());
        }
        // 2.5. 获取字段
        Field[] fields = clazz.getFields();
        for (Field field : fields) {
            System.out.println(field.getName());
        }
        // 2.6. 获取方法
        Method[] methods = clazz.getMethods();
        for (Method method : methods) {
            System.out.println(method.getName());
        }
    }
}

3. Four ways to create Class objects

public class Demo {
    public static void main(String[] args) throws
        Exception {
        // 第一种方式:调用Class.forName()
        Class clazz =Class.forName("java.lang.String");
        // 第二种方式:通过类的字节码文件来创建
        Class clazz1 = String.class;
        // 第三种方式:通过调用对象的getClass()方法来创建
        String str = new String();
        Class clazz2 = str.getClass();
        // 第四种:通过类装载器来创建
        ClassLoader loader =String.class.getClassLoader();
        Class<?> clazz3 =loader.loadClass("java.lang.String");
    }
}

The above is the detailed content of What is the meaning and role of reflection in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete