选择:
你可以从java调用java编译器,创建一个类,动态调用。这对于几行代码片段来说太过分了。
如果您的“20 条指令”都是类似的形式,并且您的词汇量有限,那么您可以创建自己的“指令集”并使用一些调度功能关闭它。(这是任何语言的通用解决方案。)
如果您使用过 Lisp 等功能更强大的语言,一些可用的 java 脚本语言也有 eval 函数。
我喜欢 groovy,因为它两全其美:动态和功能使用、闭包、交互式、探索性(例如,变量和方法上的选项卡完成),并且是 java 语言的超集,可以使用所有现有的 java 类和罐子。易于嵌入一个 groovy 控制台以弹出(甚至从您的服务器)并交互式地四处浏览、检查值等。
下面是从 groovy shell 评估代码的示例;从 Java 调用它实际上是相同的;见http://groovy.codehaus.org/Embedding+Groovy
$ groovysh
Groovy Shell (1.8.4, JVM: 1.6.0_24)
Type 'help' or '\h' for help.
---------------------------------------------------------------------------------------------
groovy:000> class Athing { String name; public Athing(String name){ this.name=name; }; String getText() { return name + "'s getText() returns..."; }; }
===> true
groovy:000> a1 = new Athing("a1"); a2 = new Athing("a-two"); a3 = new Athing("A_3");
===> Athing@6e7616ad
groovy:000> a1.getText() // showing
===> a1's getText() returns...
groovy:000> b = new Binding();
===> groovy.lang.Binding@2c704cf5
groovy:000> array = [ 'not','set','yet' ] // create an array for return values
===> [not, set, yet]
groovy:000> b.setVariable( "a1", a1 ); b.setVariable( "a2", a2 ); b.setVariable( "a3", a3 ); b.setVariable( "array", array );
===> null
groovy:000> shell = new GroovyShell(binding);
===> groovy.lang.GroovyShell@24fe2558
groovy:000> code = "array[1] = a1.getText();\n" + "array[2] = a2.getText();\n" + "array[3] = a3.getText();\n";
===> array[1] = a1.getText();
array[2] = a2.getText();
array[3] = a3.getText();
groovy:000> array // value of array before
===> [not, set, yet]
groovy:000> shell.evaluate( code ); // evaluate the string of code we were given
===> A_3's getText() returns...
groovy:000> array
===> [not, a1's getText() returns..., a-two's getText() returns..., A_3's getText() returns...]
groovy:000>