LoginSignup
16
5

More than 3 years have passed since last update.

アノテーションのインスタンスはDynamic Proxy

Posted at

アノテーションのインスタンスはDynamic Proxyです。

確認してみる

こんな感じのアノテーションを定義して、

package com.example;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface FooBar {
}

こんな感じでアノテーションのインスタンスからClassを書き出すコードを書いて、

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());
    }
}

実行すると次の出力を得られました。

出力
class com.sun.proxy.$Proxy1

ご覧の通り(?)Dynamic Proxyですね。

Dynamic Proxyはどこで作られているのか

Class.getAnnotationを辿るとAnnotationParser.annotationForMapへ行き着きます。

コードを見るとアノテーションのClassを使ってDynamic Proxyが作られていることが分かります。

    /**
     * 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));
            }});
    }

Dynamic Proxyを作るときに渡されるInvocationHandler実装はAnnotationInvocationHandlerです。
アノテーションに対するメソッド呼び出しは全てAnnotationInvocationHandlerによって処理されます。

アノテーションのインスタンスからAnnotationInvocationHandlerを取得したくなったらProxy.getInvocationHandlerを使います。

final FooBar a = ...
final InvocationHandler h = Proxy.getInvocationHandler(a);
System.out.println(h.getClass());
出力
class sun.reflect.annotation.AnnotationInvocationHandler

補足情報

そもそもDynamic Proxyってなんや?という方はProxyInvocationHandlerのJavadocをご参照ください。

16
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
5