Home > Java > javaTutorial > body text

How does Java reflection mechanism call methods?

王林
Release: 2024-04-15 16:21:01
Original
1021 people have browsed it

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".

How does Java reflection mechanism call methods?

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:

  1. Get the Class object: Use Class.forName() to get the Class object of the class.
  2. Get the method object: Use getMethod() or getMethods() to get the Method object of the method.
  3. Invoking the method: Use the 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);
Copy after login

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";
    }
}
Copy after login

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
Copy after login

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!

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