Run piece of code contained in a String

I have a piece of Java code in a String.

String javaCode = "if(polishScreenHeight >= 200 && " +
    "polishScreenHeight <= 235 && polishScreenWidth >= 220) { }";

Is it possible to convert this Java String to a Java statement and run it? Possibly using Java reflection?


Solution 1:

As has already been suggested you can compile, save and run code on the fly using the Compiler API.

Another neat alternative would be to use beanshell. Beanshell is no longer actively developed, but I can vouch for it's reliability, I've used it successfully in multiple production projects.

Solution 2:

Use BeanShell. There's a page on how to use it from Java.

Solution 3:

Beanshell (as Boris suggested) is a way to "execute" java source code. But it looks like, you want to "execute" fragments that can interact with the compiled classes. Your example contains variabe names.

Reflection will definitly not help, because reflection targets classes ("classfiles").

You could try to define a complete class ("valid java source file"), compile it and load it (url classloader). Then you should be able to use the methods from that "live generated class". But once a class is loaded, you can't get rid of it (unload), so this will work only once (AFAIK).

Solution 4:

As far as I know there is no simple way to do this.

However, in Java 6 onwards, you can compile source code for complete classes using javax.tools.Compiler. The compiled classes can then be loaded and executed. But I don't think this will achieve what you want.

Solution 5:

Another way would be to execute your code as Groovy code, see this for an example.