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 theAnnotation
on the
object. We can use reflection to get theMethod
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 theMethod
object of theannotatedMethod
method of theMain
class.method.getAnnotations()
to get all the annotations on the method and store them in theannotations
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 theMethod
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!