Java reflection mechanism allows exploring the reflector itself, and annotations on the Method object can be obtained through reflection, including annotation type and value.
Java reflection mechanism is used in the reflector itself
Java reflection mechanism allows the program to inspect and modify the structure of the class at runtime, But it is rarely used to explore the reflection mechanism itself. This article will use a practical case to show how to use the reflection mechanism to study the operation of the reflector.
Case: Get the Annotation
on the
object. We can use reflection to get the Method
Annotations attached to the object. Here is the sample code:
import java.lang.annotation.Annotation; import java.lang.reflect.Method; public class Main { public static void main(String[] args) { try { // 获取 Method 对象 Method method = Main.class.getMethod("annotatedMethod"); // 使用反射获取注解 Annotation[] annotations = method.getAnnotations(); // 遍历并打印注解 for (Annotation annotation : annotations) { System.out.println(annotation); } } catch (NoSuchMethodException e) { e.printStackTrace(); } } @MyAnnotation("Hello, World!") public void annotatedMethod() { } }
Result:
@MyAnnotation(value=Hello, World!)
Parsing:
Main.class.getMethod("annotatedMethod")
Gets the Method
object of the annotatedMethod
method of the Main
class. method.getAnnotations()
to get all the annotations on the method and store them in the annotations
array. annotations
array and print the type and value of each annotation. This example shows how to use the reflection mechanism to obtain the annotations on the Method
object. The same principle can be used to explore any other aspect of the reflection mechanism, for example:
The above is the detailed content of How does the Java reflection mechanism work with the reflector itself?. For more information, please follow other related articles on the PHP Chinese website!