Reputation: 5392
Let's say I have the following class (or can it be done with an interface also ?) :
class MyCustomClass {
boolean myCustomMethod(int a, int b){}
}
And the following string :
Math.abs(a - b) >= 10;
Is there a way, with Byte Buddy, to inject the code from the string into a new subclass of MyCustomClass, in the method myCustomMethod ? Even if the String is processed with ANTLR before ?
So I get
class MyCustomClass_SubClassInstance extends MyCustomClass {
// I know that with ByteBuddy, all this "ceremonial" code is not needed.
boolean myCustomMethod(int a, int b){
Math.abs(a - b) >= 10; // Injected code from the string
}
}
Upvotes: 2
Views: 967
Reputation: 44032
This is not the idea behind Byte Buddy. The Byte Buddy way of doing such a thing would be to implement a class that offers the method you want to invoke and then you generate a proxy to delegate to this method invocation from the instrumented type.
Javassist offers such functionaltiy but performance-wise, it is not great to compile strings at runtime so I would try to avoid this at all costs. Especially on Android where you typically have limited ressources. Class generation is quite expensive.
Upvotes: 2
Reputation: 140427
I think you are going down the wrong way. Why use ByteBuddy to generate class code?!
Instead: use the JavaCompiler feature to simply build that class as Java source - then compile it, then use the "dynamically" compiled class.
Meaning: you are somehow overcomplicating things. You actually know what you want to end up with - so create that as java source, and programmatically turn to javac
to turn that into byte code.
For Android, the JavaSourceToDex class might be the thing to use.
Upvotes: 2