The reflection mechanism allows the program to call methods at runtime. The steps are as follows: Get the class object and get the method object. Call the method, passing in the object instance and parameters. Use reflection to call the getName() method of the Employee class and return "John Doe".
Java reflection mechanism calls methods
The Java reflection mechanism allows the program to obtain and modify class information and behavior at runtime. It is widely used in frameworks, testing and debugging tools.
Use the reflection calling method
You can use the reflection calling method through the following steps:
Class.forName()
to get the Class object of the class. getMethod()
or getMethods()
to get the Method object of the method. invoke()
method to call the method, passing in the object instance and parameters (if any). Syntax
Method method = Class.forName("ClassName").getMethod("methodName", parameterTypes); Object result = method.invoke(objectInstance, parameters);
Where:
ClassName
is the class name to be called. methodName
is the name of the method to be called. parameterTypes
is an array of method parameter types. objectInstance
is the object instance on which the method is to be called (if the method is a non-static method). parameters
is the array of parameters to be passed to the method. Practical case
Suppose there is a Employee
class with the following methods:
public class Employee { public String getName() { return "John Doe"; } }
Now, let We use the reflection mechanism to call the getName()
method:
Class<?> employeeClass = Class.forName("Employee"); Method getNameMethod = employeeClass.getMethod("getName"); String name = (String) getNameMethod.invoke(new Employee()); System.out.println(name); // 输出:John Doe
In this example, we first obtain the Class object of the Employee
class. Then, we get the Method object for the getName()
method. Finally, we create an instance of the Employee
object and call the getName()
method using reflection.
The above is the detailed content of How does Java reflection mechanism call methods?. For more information, please follow other related articles on the PHP Chinese website!