Statement from text file to code

Viewed 66

I was wondering if it is possible to convert conditional statements from a text file straight to code. For example, if in a text file I had:

if(a.getId()==1){System.out.println("YES");}

Is it possible to directly call that into a program, such as this:

for(Node a : nodes){
 >>> The statement from file <<<
}

Hope that makes sense, and thanks in advance. :)

2 Answers

The simplest option would be to use a script engine. Or you can use GroovyShell which is straight forward. Example below.

Binding binding = new Binding();
GroovyShell gShell = new GroovyShell(binding);
Object result= shell.evaluate("int a = 10; a = a + 5; return a");

Not really. Java is compiled, not interpreted. I've seen template engines that generate complete java classes and then compile them into runnable code but it gets pretty hairy pretty quick.

Related