The steps to create an object through the Java reflection mechanism are as follows: Load the target class: Use the Class.forName() method. Get the constructor: use the getDeclaredConstructor() method. Create an object: Use the newInstance() method to pass parameters.
How to use Java reflection mechanism to create objects
Introduction
Java Reflection Mechanism Allows a program to inspect and modify a class's properties and methods at runtime. One of the useful features is the ability to create objects using reflection, which can be very useful in certain scenarios.
Steps to create objects by reflection
Class.forName()
method to load the object The target class in which the object is created. getDeclaredConstructor()
method to get the class constructor with the specified parameter list. newInstance()
method, passing the actual parameters to create a new instance of this constructor. Code Example
import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; 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 ObjectCreationViaReflection { public static void main(String[] args) { Class<?> personClass = null; try { // 加载 Person 类 personClass = Class.forName("Person"); // 获取带两个参数的构造函数 Constructor<?> constructor = personClass.getDeclaredConstructor(String.class, int.class); // 使用构造函数创建对象 Person person = (Person) constructor.newInstance("John Doe", 30); // 访问创建对象的属性 System.out.println("Name: " + person.getName()); System.out.println("Age: " + person.getAge()); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } }
Practical Case
A common use of reflection to create objects is to use configuration files to Dynamically load and instantiate classes. For example, you can configure a properties file that contains the fully qualified name of the class to be instantiated and the corresponding parameters. The application can then use reflection to read the configuration from the configuration file and create the corresponding objects.
Notes
There are some things to note when using reflection to create objects:
The above is the detailed content of How to create objects using Java reflection mechanism?. For more information, please follow other related articles on the PHP Chinese website!