Home > Java > javaTutorial > How does the Java reflection mechanism call the constructor?

How does the Java reflection mechanism call the constructor?

WBOY
Release: 2024-04-15 13:00:02
Original
1097 people have browsed it

The reflection mechanism can call the constructor method through the Constructor.newInstance() method, passing the actual parameter list to create the object. This method requires that the constructor type and order match, and the constructor must be public or have appropriate access permissions.

How does the Java reflection mechanism call the constructor?

Java reflection mechanism calls the constructor

Java reflection mechanism provides dynamic access to classes, allowing inspection and Modify the class and its members. Through reflection, we can call class constructor methods to create new objects.

Syntax:

To use reflection to call the constructor, you can use the Constructor.newInstance() method. The syntax is as follows:

Object newInstance(Object... args) throws InstantiationException, IllegalAccessException, InvocationTargetException
Copy after login

Where:

  • args: The actual parameter list used to construct the object

Practical case:

We create a class named Person and provide a constructor with parameters:

public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}
Copy after login

Now, we can use reflection call This constructor:

// 创建 Class 对象
Class<?> personClass = Class.forName("Person");

// 获取带有两个参数的构造方法
Constructor<?> constructor = personClass.getConstructor(String.class, int.class);

// 调用构造方法创建对象
Object person = constructor.newInstance("John", 30);
Copy after login

Objects called using reflection can be accessed like normal objects:

System.out.println(((Person) person).getName()); // 输出: John
System.out.println(((Person) person).getAge()); // 输出: 30
Copy after login

Notes:

  • Call the constructor Methods need to be passed the correct parameter types and order.
  • The called constructor must be public or have appropriate access permissions.
  • If the constructor throws an exception, newInstance() will wrap the exception in an InvocationTargetException and throw it.

The above is the detailed content of How does the Java reflection mechanism call the constructor?. For more information, please follow other related articles on the PHP Chinese website!

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