Gunnar
Gunnar

Reputation: 19020

Proxy instantiation fails if proxied class has package-private default constructor

Using ByteBuddy, I'd like to create a proxy for a type which has a package private default constructor. That's the type:

public class Foo {

    Foo() {
    }
}

And that's my code for proxy creation and instantiation:

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

So I am trying to add public default constructor to my proxy type, intercept its invocation and delegate to the super type constructor. This fails though with an IllegalAccessException in the generated constructor:

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)

As the proxy is in the same package as the proxied class, it's not clear to my why that invocation fails. What am I doing wrong here? Is there another way to have a proxy invoke a super constructor with default visibility?

Upvotes: 2

Views: 259

Answers (1)

Ashraff Ali Wahab
Ashraff Ali Wahab

Reputation: 1108

The classes are being loaded by two different class loaders. Please change your strategy to INJECTION and try.

ClassLoadingStrategy.Default.INJECTION

Upvotes: 3

Related Questions