2

ByteBuddy を使用して、パッケージのプライベート デフォルト コンストラクターを持つ型のプロキシを作成したいと思います。それはタイプです:

public class Foo {

    Foo() {
    }
}

そして、それはプロキシの作成とインスタンス化のための私のコードです:

public class CreateAndExecuteProxy {

    public static void main(String[] args) throws Exception {
        Constructor<?> superConstructor = Foo.class.getDeclaredConstructor();

        Class<? extends Foo> proxyType = new ByteBuddy()
                .subclass( Foo.class, ConstructorStrategy.Default.NO_CONSTRUCTORS )
                .defineConstructor( Visibility.PUBLIC )
                .intercept( MethodCall.invoke( superConstructor ).onSuper() )
                .make()
                .load( CreateAndExecuteProxy.class.getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
                .getLoaded();

        Foo foo = proxyType.newInstance();
    }
}

そのため、パブリックのデフォルト コンストラクターをプロキシ タイプに追加し、その呼び出しをインターセプトして、スーパー タイプ コンストラクターに委譲しようとしています。IllegalAccessExceptionこれは、生成されたコンストラクターで失敗します。

Exception in thread "main" java.lang.IllegalAccessError:
tried to access method com.example.proxy.test.Foo.&lt;init&gt;()V from class com.example.proxy.test.Foo$ByteBuddy$65mxf95M
  com.example.proxy.test.Foo$ByteBuddy$65mxf95M.&lt;init&gt;(Unknown Source)
  ...
  at java.lang.Class.newInstance(Class.java:442)
  at com.example.proxy.test.CreateAndExecuteProxy.main(CreateAndExecuteProxy.java:33)

プロキシはプロキシされたクラスと同じパッケージにあるため、その呼び出しが失敗する理由は明確ではありません。ここで何が間違っていますか?プロキシがデフォルトの可視性でスーパーコンストラクターを呼び出す別の方法はありますか?

4

1 に答える 1

3

クラスは、2 つの異なるクラス ローダーによってロードされています。作戦をインジェクションに変えて挑戦してみてください。

ClassLoadingStrategy.Default.INJECTION

于 2016-02-17T12:01:59.720 に答える