Extract from text file to code

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

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

Is it possible to directly call this into a program, for example:

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

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

+4
source share
2 answers

The easiest option is to use the script engine. Or you can use GroovyShell  which is straightforward. An example is below.

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

Not really. Java is compiled, not interpreted. I have seen template engines that generate full Java classes and then compile them into executable code, but it is quite hairy.

0
source

All Articles