Java 运行包含在字符串中的一段代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4389232/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Run piece of code contained in a String
提问by blue-sky
I have a piece of Java code in a String.
我在字符串中有一段 Java 代码。
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?
是否可以将此 Java 字符串转换为 Java 语句并运行它?可能使用Java反射?
采纳答案by Joel
As has already been suggested you can compile, save and run code on the fly using the Compiler API.
正如已经建议的那样,您可以使用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.
另一个巧妙的选择是使用beanshell。Beanshell 不再积极开发,但我可以保证它的可靠性,我已经在多个生产项目中成功使用了它。
回答by Steve McLeod
As far as I know there is no simple way to do this.
据我所知,没有简单的方法可以做到这一点。
However, in Java 6 onwards, you cancompile source code for complete classes using javax.tools.Compiler. The compiled classes can then be loaded and executed. But I don't think this will achieve what you want.
但是,从 Java 6 开始,您可以使用 javax.tools.Compiler 编译完整类的源代码。然后可以加载和执行编译的类。但我认为这不会实现你想要的。
回答by Boris Pavlovi?
Use BeanShell. There's a page on how to use it from Java.
使用 BeanShell。有一个关于如何从 Java 使用它的页面。
回答by Mike
Try the JavaCompilerAPI.
试试JavaCompilerAPI。
Someone else answered this way better than I could, though: Convert String to Code
不过,有人比我更好地回答了这种方式: 将字符串转换为代码
Be careful before actually using something like this...
在实际使用这样的东西之前要小心......
回答by Andreas Dolk
Beanshell (as Boris suggested) is a way to "execute" java source code. But it looks like, you want to "execute" fragments that can interact with the compiled classes. Your example contains variabe names.
Beanshell(正如鲍里斯所建议的)是一种“执行”java 源代码的方法。但看起来,您想要“执行”可以与编译类交互的片段。您的示例包含变量名称。
Reflection will definitly not help, because reflection targets classes ("classfiles").
反射肯定无济于事,因为反射针对的是类(“类文件”)。
You couldtry to define a complete class ("valid java source file"), compile it and load it (url classloader). Then you should be able to use the methods from that "live generated class". But once a class is loaded, you can't get rid of it (unload), so this will work only once (AFAIK).
您可以尝试定义一个完整的类(“有效的 Java 源文件”),编译并加载它(url 类加载器)。然后您应该能够使用该“实时生成的类”中的方法。但是一旦一个类被加载,你就无法摆脱它(卸载),所以这只会工作一次(AFAIK)。
回答by pgras
回答by Lasitha Lakmal
you can use this code to run method from using this code
new Statement(Object target, String methodName, Object[] arguments).execute();
您可以使用此代码运行此代码的方法
new Statement(Object target, String methodName, Object[] arguments).execute();
import java.beans.Statement;
public class HelloWorld {
public void method_name(String name) {
System.out.println(name);
}
public static void main(String[] args) throws Exception {
HelloWorld h = new HelloWorld();
new Statement(h, "method_name", new Object[]{"Hello world"}).execute();
}
}
回答by Jonas_Hess
It is not Java, but as pgrashas already suggested you could use GrooyScript like so :
它不是 Java,但正如pgras已经建议您可以像这样使用 GrooyScript:
Binding binding = new Binding();
GroovyShell shell = new GroovyShell(binding);
String[] strings = new String[]{"World", "Groovy"};
shell.setVariable("args", strings);
String script = "return \"Hello \" + args[1]";
String value = (String) shell.evaluate(script);
System.out.println(value); // Hello Groovy
回答by Peru
- Please reevaluate your design and this should be your last alternative.
- You should validate the sanity of the String which will be executed to avoid future injection attack.
- 请重新评估您的设计,这应该是您最后的选择。
- 您应该验证将要执行的字符串的完整性,以避免未来的注入攻击。
Now If you can have the String as JavaScriptthen below code should help,
现在,如果您可以将字符串作为JavaScript,那么下面的代码应该会有所帮助,
public class EvalScript {
public static void main(String[] args) throws Exception {
// create a script engine manager
ScriptEngineManager factory = new ScriptEngineManager();
// create a JavaScript engine
ScriptEngine engine = factory.getEngineByName("JavaScript");
// below JS function is executed.
/*
* student object value will be provided by the program as the JSON String.
function checkStudentElgibility(student){
if(student.age >= 10 && student.currentGrade >= 5){
return true;
}
}
// student object value will be provided by the program as the JSON String
checkStudentElgibility(student);
*/
String studentJsonString = "{\n" +
" \"age\" : 10,\n" +
" \"currentGrade\" : 5\n" +
"}";
String javaScriptFunctionString = "function checkStudentElgibility(student){\n" +
" if(student.age >= 10 && student.currentGrade >= 5){\n" +
" return true;\n" +
" }\n" +
"}\n" +
"checkStudentElgibility(student);";
StringBuilder javaScriptString = new StringBuilder();
javaScriptString.append("student=");
javaScriptString.append(studentJsonString);
javaScriptString.append("\n");
javaScriptString.append(javaScriptFunctionString);
Object object = engine.eval(javaScriptString.toString());
System.out.println(object);
// You can also pass the object as follows,
// evaluate JavaScript code that defines an object with one method
engine.eval("var obj = new Object()");
engine.eval("obj.hello = function(name) { print('Hello, ' + name)
}");
// expose object defined in the script to the Java application
Object obj = engine.get("obj");
// create an Invocable object by casting the script engine object
Invocable inv = (Invocable) engine;
// invoke the method named "hello" on the object defined in the
// in js Object with "Script Method" as parameter
inv.invokeMethod(obj, "hello", "Script Method!");
// You can also use Java Objects as Java script object and you can also pass Objects as reference inside Java script function
String jsString = " var obj = new Object()\n" +
" var ArrayList = Java.type(\"java.util.ArrayList\");\n" +
" var customSizeArrayList = new ArrayList(16);\n" +
" obj.hello = function(name) { \n" +
" customSizeArrayList(name); \n" +
" print('Hello, ' + name) \n" +
" }";
}
}
Reference : https://docs.oracle.com/javase/8/docs/technotes/guides/scripting/prog_guide/javascript.html#A1147187
参考:https: //docs.oracle.com/javase/8/docs/technotes/guides/scripting/prog_guide/javascript.html#A1147187