Reputation: 721
I know there is already many question about turning a string into runnable code, but my question is a little different. Lets say you have a class with a method called: public boolean isSame(boolean a, boolean b)
, and a String that contains: "if(a == b) { return true; } return false"
. Is there a way to add the contents of the string to the code of the method? So the final result will be:
public boolean isSame(boolean a, boolean b){
if(a == b){
return true;
}
return false;
}
Thank you very much.
Edit: I totally understand if this is not possible, but it is worth asking :).
Upvotes: 3
Views: 109
Reputation: 28746
Perhaps you could use the BECL library - it's a byte code engineering library that, although not renowned for performance, is renowned for ease of use.
The thing that makes it interesting in your case:
Unlike other byte code engineering libraries that provide an abstraction on top of byte-code, it works by decompiling a class, weaving in the required code and then compiling it again. . . and this happens for the the class loading phase. . . theoretically this would allow you to insert valid code in a string format before or after the original method invocation.
Essentially using the compiler as per suggestions in the comments section of your question, but does a little extra work for you.
Upvotes: 1