Reputation: 19020
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.<init>()V from class com.example.proxy.test.Foo$ByteBuddy$65mxf95M
com.example.proxy.test.Foo$ByteBuddy$65mxf95M.<init>(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
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