Home > Java > javaTutorial > How to use Java language reflection

How to use Java language reflection

WBOY
Release: 2023-06-10 18:58:15
Original
1099 people have browsed it

Java language is an object-oriented programming language, which has the advantages of good cross-platform and easy maintenance. The Java language reflection mechanism is an important feature of the Java language. It allows the program to dynamically obtain information about a certain class at runtime and use the methods and attributes provided by the class, thereby improving the scalability and flexibility of the program. . This article will introduce how to use Java language reflection.

The reflection mechanism is a dynamic mechanism in the Java language, which allows programmers to dynamically obtain class information when writing code, including class constructors, methods and properties. The reflection mechanism of the Java language mainly consists of three classes: Class, Constructor and Method. Among them, Class represents the type of the class, Constructor represents the constructor of the class, and Method represents the method of the class.

Through the Class class object, we can obtain the complete information of the class, including class name, parent class, interface, constructor method, member method, member attribute, annotation, etc. For example, the following code demonstrates obtaining the class name and parent class name of a class:

public class Person {
    private String name;
    private int age;
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public int getAge() {
        return age;
    }
}

public class Main {
    public static void main(String[] args) {
        Class<Person> pClass = Person.class;
        System.out.println("类名:" + pClass.getName());
        System.out.println("父类名:" + pClass.getSuperclass().getName());
    }
}
Copy after login

In the above code, we obtain the of the Person class through Person.class Class type, then you can use the getName() method to get the name of the class, use the getSuperClass() method to get the parent class of the class, and finally output the class name and parent class name .

In addition to getting the class name and parent class name, we can also get information about other classes through reflection, such as getting the class's constructor, member methods, member properties, etc. The following code demonstrates how to get the Person class Constructors, member variables and member methods, and call them through reflection:

public class Person {
    private String name;
    private int age;
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public int getAge() {
        return age;
    }
    public void sayHello() {
        System.out.println("Hello, my name is " + name);
    }
}

public class Main {
    public static void main(String[] args) throws Exception {
        Class<Person> pClass = Person.class;
        // 获取所有构造器
        Constructor<?>[] constructors = pClass.getDeclaredConstructors();
        // 获取指定的构造器
        Constructor<?> constructor = pClass.getDeclaredConstructor(String.class, int.class);
        // 新建对象
        Person person = (Person) constructor.newInstance("Tom", 20);
        // 获取所有成员变量
        Field[] fields = pClass.getDeclaredFields();
        // 获取指定的成员变量
        Field field = pClass.getDeclaredField("name");
        // 修改成员变量的值
        field.setAccessible(true);
        field.set(person, "Jerry");
        // 获取所有成员方法
        Method[] methods = pClass.getDeclaredMethods();
        // 获取指定的成员方法
        Method method = pClass.getDeclaredMethod("sayHello");
        // 调用成员方法
        method.invoke(person);
    }
}
Copy after login

In the above code, we use the getDeclaredConstructors() method to get all the constructors of the Person class, Then use getDeclaredConstructor(String.class, int.class) to obtain the specified constructor, and use the newInstance() method to create a new object. Next, we use the getDeclaredFields() method to obtain all member variables of the Person class, use the getDeclaredField("name") method to obtain the specified member variable, and use setAccessible( true) method calls private member variables. Finally, we use the getDeclaredMethods() method to get all member methods of the Person class, use the getDeclaredMethod("sayHello") method to get the specified member method, and use invoke( ) method calls member method.

When using the reflection mechanism, you need to pay attention to the following points:

  1. The performance of the reflection mechanism is low because it needs to obtain class information at runtime, which is not required at compile time. The information has already been determined, so reflection mechanisms should be avoided where possible.
  2. The reflection mechanism can access and modify the private properties and private methods of the class, which breaks the encapsulation of the class and should be used with caution to avoid adverse effects.
  3. The reflection mechanism needs to handle exceptions, such as NoSuchMethodException, IllegalAccessException, etc., so you should pay attention to exception handling when using the reflection mechanism.

In short, the reflection mechanism of the Java language is a very important feature. It allows the program to dynamically obtain class information and use class methods and attributes, improving the scalability and flexibility of the program. sex. When using the reflection mechanism, you need to pay attention to issues such as performance, encapsulation, and exception handling to ensure the quality and reliability of the code.

The above is the detailed content of How to use Java language reflection. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template