I have the following unit test :
@Test
public void TestPrivateMethodDelegation() throws InstantiationException, IllegalAccessException, IllegalArgumentException,
InvocationTargetException, NoSuchMethodException, SecurityException
{
Foo foo = new ByteBuddy()
.subclass(Foo.class)
.method(named("getHello")
.and(isDeclaredBy(Foo.class)
.and(returns(String.class))))
.intercept(MethodDelegation.to(new Bar()))
.make()
.load(Foo.class.getClassLoader(), ClassReloadingStrategy.fromInstalledAgent())
.getLoaded()
.getDeclaredConstructor().newInstance();
Method privateMethod = Foo.class.getDeclaredMethod("getHello");
privateMethod.setAccessible(true);
assertEquals(privateMethod.invoke(foo), new Bar().getHello());
}
Here are the classes it uses :
@NoArgsConstructor
public class Foo
{
@SuppressWarnings("unused")
private String getHello()
{
return "Hello Byte Buddy!";
}
}
@NoArgsConstructor
public class Bar
{
public String getHello()
{
return "Hello Hacked Byte Buddy!";
}
}
When i make the getHello() method public in the Foo class, this test passes. When i leave it private, the test fails since i can only assume the private method is not properly delegated.
Is it even possible to delegate a private method to another class?
Thanks!
No, it is not. Byte Buddy generates byte code just as javac would do and this byte code must be valid to function. You cannot call a private method from another class, therefore, Byte Buddy is throwing an exception.