Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 763
blue-sky Avatar asked Dec 08 '10 15:12

blue-sky


People also ask

How do you run a string in Java?

Java String class provides a lot of methods to perform operations on strings such as compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc. The java. lang. String class implements Serializable, Comparable and CharSequence interfaces.


1 Answers

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.

like image 106
Joel Avatar answered Sep 21 '22 07:09

Joel