The instance of the annotation is the Dynamic Proxy.
Define an annotation like this,
package com.example;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface FooBar {
}
Write the code to write Class
from the annotation instance like this,
package com.example;
@FooBar
public class Main {
public static void main(final String[] args) {
final FooBar a = Main.class.getAnnotation(FooBar.class);
System.out.println(a.getClass());
}
}
When I ran it, I got the following output:
output
class com.sun.proxy.$Proxy1
As you can see (?) Dynamic Proxy.
If you follow Class.getAnnotation
, you will reach ʻAnnotationParser.annotationForMap`.
Looking at the code, you can see that the Dynamic Proxy is created using the annotation Class
.
/**
* Returns an annotation of the given type backed by the given
* member {@literal ->} value map.
*/
public static Annotation annotationForMap(final Class<? extends Annotation> type,
final Map<String, Object> memberValues)
{
return AccessController.doPrivileged(new PrivilegedAction<Annotation>() {
public Annotation run() {
return (Annotation) Proxy.newProxyInstance(
type.getClassLoader(), new Class<?>[] { type },
new AnnotationInvocationHandler(type, memberValues));
}});
}
The ʻInvocationHandler implementation passed when creating a Dynamic Proxy is ʻAnnotationInvocationHandler
.
All method calls to annotations are handled by ʻAnnotationInvocationHandler`.
If you want to get ʻAnnotationInvocationHandler from an instance of Annotation, use
Proxy.getInvocationHandler`.
final FooBar a = ...
final InvocationHandler h = Proxy.getInvocationHandler(a);
System.out.println(h.getClass());
output
class sun.reflect.annotation.AnnotationInvocationHandler
What is Dynamic Proxy in the first place? Please refer to the Javadoc of Proxy
and ʻInvocationHandler`.
Recommended Posts