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.
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 objectPractical 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:
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!