com.sun.proxy.$Proxyとは?

異なるフレームワーク(例えばEJB仕様を実装したフレームワークやJPAプロバイダなど)の深い部分でエラーが発生した場合、スタックトレースに com.sun.proxy.$Proxy のようなクラスが含まれていることを見たことがあります。Proxyが何であるかは知っていますが、私はより技術的でよりJavaに特化した答えを探しています。

1.どんなものなのか? 2.どのように作られるのか? 3.JVMとどのような関係があるのか?JVMの実装に依存するのか?

ソリューション

1.プロキシは、実行時に作成されロードされるクラスです。これらのクラスには、ソースコードはありません。コードがないのに、どうやって何かをさせるのか、不思議に思っている方もいらっしゃると思います。その答えは、作成時に InvocationHandler を実装したオブジェクトを指定し、プロキシメソッドが呼び出されたときに呼び出されるメソッドを定義しているからです。

2.呼び出しを使って作成します。

    Proxy.newProxyInstance(classLoader, interfaces, invocationHandler)

その論拠は

1. `classLoader`.クラスが生成されると、このクラスローダーで読み込まれる。
2. `interfaces`.クラスオブジェクトの配列で、すべてインターフェースでなければならない。生成されたプロキシは、これらのインターフェイスをすべて実装する。
3. `invocationHandler`.これは、メソッドが呼び出されたときにプロキシが何をすべきかを知る方法である。これは `InvocationHandler` を実装したオブジェクトである。サポートされているインターフェースのいずれか、つまり `hashCode`、`equals`、`toString` のメソッドが呼び出されると、ハンドラ上で `invoke` というメソッドが呼び出され、呼び出されるメソッドの `Method` オブジェクトと渡された引数が渡される。

これについては、Proxyクラスのドキュメントを参照してください。

3.バージョン1.3以降のJVMの実装は、必ずこれらをサポートする必要があります。これらは、実装固有の方法でJVMの内部データ構造に読み込まれますが、動作は保証されています。

解説 (0)

どんなものですか?

特別なことはありません。一般的なJavaのクラスインスタンスと同じです。

しかし、これらのクラスは java.lang.reflect.Proxy#newProxyInstance によって作られた Synthetic Proxy Class である。

JVMとの関係は?JVMの実装に特化したものなのか?

1.3から導入された

http://docs.oracle.com/javase/1.3/docs/relnotes/features.html#reflection

Javaの一部であるため、各JVMはこれをサポートする必要があります。

どのように作成されるのでしょうか(Openjdk7ソース)。

要するに、JVMのASM技術(実行時にジャババイトコードを定義する)を使って作成されているのです。

同じ技術を使ったものがある。

java.lang.reflect.Proxy#newProxyInstance` を呼び出したらどうなるか?

  1. ソースを読むと、newProxyInstanceが getProxyClass0 を呼び出して Class<? を取得します。 1.たくさんのキャッシュや何かの後に、魔法のようなProxyGenerator.generateProxyClass` を呼び出し、byte[]を返します。
  2. ClassLoader define class を呼び出して、生成された $Proxy クラス(見たことのあるクラス名)をロードする。 1.インスタンス化するだけですぐに使える

magic sun.misc.ProxyGenerator の中で起こること。

  1. インターフェースに含まれるすべてのメソッドを1つにまとめたクラス(バイトコード)を作成する。

  2. 各メソッドは、以下のような同じバイトコードでビルドされます。

    1.呼び出し方法メス情報(生成時に保存)を取得する。

    1. 割り込みハンドラ'のinvoke()` に情報を渡す。
    2. invocation ハンドラ'の invoke() から戻り値を取得する。 1.ただ返すだけ
  3. クラス(バイトコード)をバイト[]の形で表現する。

授業の描き方について

Javaのコードがバイトコードにコンパイルされていると考えて、実行時に以下のように実行します。

Talk is cheap show you the code

sun/misc/ProxyGenerator.java のコアメソッド。

generateClassFile

/**
 * Generate a class file for the proxy class.  This method drives the
 * class file generation process.
 */
private byte[] generateClassFile() {

    /* ============================================================
     * Step 1: Assemble ProxyMethod objects for all methods to
     * generate proxy dispatching code for.
     */

    /*
     * Record that proxy methods are needed for the hashCode, equals,
     * and toString methods of java.lang.Object.  This is done before
     * the methods from the proxy interfaces so that the methods from
     * java.lang.Object take precedence over duplicate methods in the
     * proxy interfaces.
     */
    addProxyMethod(hashCodeMethod, Object.class);
    addProxyMethod(equalsMethod, Object.class);
    addProxyMethod(toStringMethod, Object.class);

    /*
     * Now record all of the methods from the proxy interfaces, giving
     * earlier interfaces precedence over later ones with duplicate
     * methods.
     */
    for (int i = 0; i < interfaces.length; i++) {
        Method[] methods = interfaces[i].getMethods();
        for (int j = 0; j < methods.length; j++) {
            addProxyMethod(methods[j], interfaces[i]);
        }
    }

    /*
     * For each set of proxy methods with the same signature,
     * verify that the methods' return types are compatible.
     */
    for (List sigmethods : proxyMethods.values()) {
        checkReturnTypes(sigmethods);
    }

    /* ============================================================
     * Step 2: Assemble FieldInfo and MethodInfo structs for all of
     * fields and methods in the class we are generating.
     */
    try {
        methods.add(generateConstructor());

        for (List sigmethods : proxyMethods.values()) {
            for (ProxyMethod pm : sigmethods) {

                // add static field for method's Method object
                fields.add(new FieldInfo(pm.methodFieldName,
                    "Ljava/lang/reflect/Method;",
                     ACC_PRIVATE | ACC_STATIC));

                // generate code for proxy method and add it
                methods.add(pm.generateMethod());
            }
        }

        methods.add(generateStaticInitializer());

    } catch (IOException e) {
        throw new InternalError("unexpected I/O Exception");
    }

    if (methods.size() > 65535) {
        throw new IllegalArgumentException("method limit exceeded");
    }
    if (fields.size() > 65535) {
        throw new IllegalArgumentException("field limit exceeded");
    }

    /* ============================================================
     * Step 3: Write the final class file.
     */

    /*
     * Make sure that constant pool indexes are reserved for the
     * following items before starting to write the final class file.
     */
    cp.getClass(dotToSlash(className));
    cp.getClass(superclassName);
    for (int i = 0; i < interfaces.length; i++) {
        cp.getClass(dotToSlash(interfaces[i].getName()));
    }

    /*
     * Disallow new constant pool additions beyond this point, since
     * we are about to write the final constant pool table.
     */
    cp.setReadOnly();

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    DataOutputStream dout = new DataOutputStream(bout);

    try {
        /*
         * Write all the items of the "ClassFile" structure.
         * See JVMS section 4.1.
         */
                                    // u4 magic;
        dout.writeInt(0xCAFEBABE);
                                    // u2 minor_version;
        dout.writeShort(CLASSFILE_MINOR_VERSION);
                                    // u2 major_version;
        dout.writeShort(CLASSFILE_MAJOR_VERSION);

        cp.write(dout);             // (write constant pool)

                                    // u2 access_flags;
        dout.writeShort(ACC_PUBLIC | ACC_FINAL | ACC_SUPER);
                                    // u2 this_class;
        dout.writeShort(cp.getClass(dotToSlash(className)));
                                    // u2 super_class;
        dout.writeShort(cp.getClass(superclassName));

                                    // u2 interfaces_count;
        dout.writeShort(interfaces.length);
                                    // u2 interfaces[interfaces_count];
        for (int i = 0; i < interfaces.length; i++) {
            dout.writeShort(cp.getClass(
                dotToSlash(interfaces[i].getName())));
        }

                                    // u2 fields_count;
        dout.writeShort(fields.size());
                                    // field_info fields[fields_count];
        for (FieldInfo f : fields) {
            f.write(dout);
        }

                                    // u2 methods_count;
        dout.writeShort(methods.size());
                                    // method_info methods[methods_count];
        for (MethodInfo m : methods) {
            m.write(dout);
        }

                                     // u2 attributes_count;
        dout.writeShort(0); // (no ClassFile attributes for proxy classes)

    } catch (IOException e) {
        throw new InternalError("unexpected I/O Exception");
    }

    return bout.toByteArray();
}

addProxyMethod

/**
 * Add another method to be proxied, either by creating a new
 * ProxyMethod object or augmenting an old one for a duplicate
 * method.
 *
 * "fromClass" indicates the proxy interface that the method was
 * found through, which may be different from (a subinterface of)
 * the method's "declaring class".  Note that the first Method
 * object passed for a given name and descriptor identifies the
 * Method object (and thus the declaring class) that will be
 * passed to the invocation handler's "invoke" method for a given
 * set of duplicate methods.
 */
private void addProxyMethod(Method m, Class fromClass) {
    String name = m.getName();
    Class[] parameterTypes = m.getParameterTypes();
    Class returnType = m.getReturnType();
    Class[] exceptionTypes = m.getExceptionTypes();

    String sig = name + getParameterDescriptors(parameterTypes);
    List sigmethods = proxyMethods.get(sig);
    if (sigmethods != null) {
        for (ProxyMethod pm : sigmethods) {
            if (returnType == pm.returnType) {
                /*
                 * Found a match: reduce exception types to the
                 * greatest set of exceptions that can thrown
                 * compatibly with the throws clauses of both
                 * overridden methods.
                 */
                List> legalExceptions = new ArrayList>();
                collectCompatibleTypes(
                    exceptionTypes, pm.exceptionTypes, legalExceptions);
                collectCompatibleTypes(
                    pm.exceptionTypes, exceptionTypes, legalExceptions);
                pm.exceptionTypes = new Class[legalExceptions.size()];
                pm.exceptionTypes =
                    legalExceptions.toArray(pm.exceptionTypes);
                return;
            }
        }
    } else {
        sigmethods = new ArrayList(3);
        proxyMethods.put(sig, sigmethods);
    }
    sigmethods.add(new ProxyMethod(name, parameterTypes, returnType,
                                   exceptionTypes, fromClass));
}

プロキシメソッドに関する全コード

    private MethodInfo generateMethod() throws IOException {
        String desc = getMethodDescriptor(parameterTypes, returnType);
        MethodInfo minfo = new MethodInfo(methodName, desc,
            ACC_PUBLIC | ACC_FINAL);

        int[] parameterSlot = new int[parameterTypes.length];
        int nextSlot = 1;
        for (int i = 0; i < parameterSlot.length; i++) {
            parameterSlot[i] = nextSlot;
            nextSlot += getWordsPerType(parameterTypes[i]);
        }
        int localSlot0 = nextSlot;
        short pc, tryBegin = 0, tryEnd;

        DataOutputStream out = new DataOutputStream(minfo.code);

        code_aload(0, out);

        out.writeByte(opc_getfield);
        out.writeShort(cp.getFieldRef(
            superclassName,
            handlerFieldName, "Ljava/lang/reflect/InvocationHandler;"));

        code_aload(0, out);

        out.writeByte(opc_getstatic);
        out.writeShort(cp.getFieldRef(
            dotToSlash(className),
            methodFieldName, "Ljava/lang/reflect/Method;"));

        if (parameterTypes.length > 0) {

            code_ipush(parameterTypes.length, out);

            out.writeByte(opc_anewarray);
            out.writeShort(cp.getClass("java/lang/Object"));

            for (int i = 0; i < parameterTypes.length; i++) {

                out.writeByte(opc_dup);

                code_ipush(i, out);

                codeWrapArgument(parameterTypes[i], parameterSlot[i], out);

                out.writeByte(opc_aastore);
            }
        } else {

            out.writeByte(opc_aconst_null);
        }

        out.writeByte(opc_invokeinterface);
        out.writeShort(cp.getInterfaceMethodRef(
            "java/lang/reflect/InvocationHandler",
            "invoke",
            "(Ljava/lang/Object;Ljava/lang/reflect/Method;" +
                "[Ljava/lang/Object;)Ljava/lang/Object;"));
        out.writeByte(4);
        out.writeByte(0);

        if (returnType == void.class) {

            out.writeByte(opc_pop);

            out.writeByte(opc_return);

        } else {

            codeUnwrapReturnValue(returnType, out);
        }

        tryEnd = pc = (short) minfo.code.size();

        List> catchList = computeUniqueCatchList(exceptionTypes);
        if (catchList.size() > 0) {

            for (Class<?> ex : catchList) {
                minfo.exceptionTable.add(new ExceptionTableEntry(
                    tryBegin, tryEnd, pc,
                    cp.getClass(dotToSlash(ex.getName()))));
            }

            out.writeByte(opc_athrow);

            pc = (short) minfo.code.size();

            minfo.exceptionTable.add(new ExceptionTableEntry(
                tryBegin, tryEnd, pc, cp.getClass("java/lang/Throwable")));

            code_astore(localSlot0, out);

            out.writeByte(opc_new);
            out.writeShort(cp.getClass(
                "java/lang/reflect/UndeclaredThrowableException"));

            out.writeByte(opc_dup);

            code_aload(localSlot0, out);

            out.writeByte(opc_invokespecial);

            out.writeShort(cp.getMethodRef(
                "java/lang/reflect/UndeclaredThrowableException",
                "", "(Ljava/lang/Throwable;)V"));

            out.writeByte(opc_athrow);
        }
解説 (0)