I want to generate byte code of a class which passes a method reference as argument to another method. e.g.:
public class GeneratedClass {
public GeneratedClass() {
Test.foo((Function)Test::getId)
}
}
Using ByteBuddy I can generate a class with custom constructor, and create an InvokeDynamic
to represent the Test::getId
, but the problem is that I cannot pass the InvokeDynamic
as a parameter to my MethodCall
. My current implementation is as follows:
var fooMethod = Test.class.getMethod("foo",Function.class);
InvokeDynamic methodRef = InvokeDynamic.lambda(Test.class.getMethod("getId"), Function.class)
.withoutArguments();
new ByteBuddy()
.subclass(Object.class, ConstructorStrategy.Default.NO_CONSTRUCTORS)
.name("GeneratedClass")
.defineConstructor(Visibility.PUBLIC)
.intercept(
MethodCall.invoke(fooMethod)
.with((Object)null) \\I want to pass the methodRef instead of null
.andThen(methodRef)
).make()
.saveIn(new File("target"));
Which generates the following:
public class GeneratedClass {
public GeneratedClass() {
Test.foo((Function)null);
Test::getId;
}
}