I want to know if there is any way to convert a String
to Java compilable code.
I have a comparative expression saved in a database field. I want to re
If you're getting the condition from a database, I'll wager there's a good chance that you might be wanting to use that condition to access data in that database.
If you're using an ORM such as JPA or Hibernate (traditional or JPA), you might be able to formulate a dynamic query expression that you'd pass to the createQuery() method. This isn't as good as being able to do an on-the-fly compile of arbitrary Java code, but maybe it's all you need, and that particular solution doesn't require any special inclusions or actions, since the query language compiler is part of the ORM system itself.
Of course, if you DO do dynamic queries that way, I'd recommend logging them somehow, since it can be a real pain to figure out what went wrong after the fact if your query string is now in the garbage collector.
It's not fair to say that this is impossible. It is a very similar problem to the problem Java Server Pages (JSPs) have - in their case, there is code embedded in HTML files that needs to be compiled into a servlet and executed. If you really wanted to use that mechanism, I'm relatively sure you could dig through the source for a servlet container and figure out how they did it (probably even reusing their mechanism to some degree.)
However; it isn't an easy problem to solve (once you solve the obvious, immediate problem, you end up having to deal with issues with classloading and related problems.)
It certainly would seem to be a better idea to go with the Java Scripting Platform in JDK6.
I have used both BeanShell and GroovyShell but performance wise, GroovyShell is way faster if you prase and cache the script.
You can't because java is a compiled language.
You, however, should use a javax.script
api to execute code in runtime.
JVM6 ships with Rhino (javascript interpreter) avaliable via javax.script
.
http://java.sun.com/javase/6/docs/api/javax/script/package-summary.html
There are javax.script
-compatible java interpreters (and bean shell) avaliable.
https://scripting.dev.java.net/
If you're willing to sacrifice the "Java code" portion of your requirement, you could use the Java Mathematic Expression Evaluator library. It allows you to specify a math expression (as a java.lang.String), add values for the variables, and then evaluate the expression.
I've used it in production code with great success.
If all you really need to do is evaluate an expression stored in a database, you might want to look at JEP (Java Expression Parser)
The latest (commercial) version is here.
A slightly older, GPL version is here
Some examples for usage.