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

How does the Java reflection mechanism call the constructor?

WBOY
WBOYOriginal
2024-04-15 13:00:021100browse

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

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;
    }
}

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);

Objects called using reflection can be accessed like normal objects:

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

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!

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