首页  >  文章  >  Java  >  如何执行存储在字符串变量中的Java代码?

如何执行存储在字符串变量中的Java代码?

Susan Sarandon
Susan Sarandon原创
2024-10-24 19:27:29444浏览

How to Execute Java Code Stored in a String Variable?

执行存储在字符串中的代码

问题:

可以执行以下 Java 代码吗?存储在字符串变量中?是否可以将这样的 String 转换为 Java 语句并运行它?

答案:

使用编译器 API

正如之前的建议中提到的,编译器 API 使您能够动态编译和执行代码。以下是如何使用它:

<code class="java">// Create a Java source code string
String javaCode = "...";

// Create a Java compiler instance
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

// Create a source code file from the string
JavaFileObject javaFile = new StringJavaFileObject("MyCode", javaCode);

// Compile the source code
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
Iterable<? extends JavaFileObject> compilationUnits = Collections.singletonList(javaFile);
compiler.getTask(null, null, diagnostics, null, null, compilationUnits).call();

// Execute the compiled code
Class<?> clazz = Class.forName("MyCode");
Method method = clazz.getDeclaredMethod("myMethod");
method.invoke(null);</code>

使用 Beanshell

或者,您可以按如下方式使用 Beanshell 库:

<code class="java">// Create a Beanshell interpreter and add the Java code to it
Interpreter interpreter = new Interpreter();
interpreter.eval(javaCode);

// Access the defined classes and methods in the interpreter
Class<?> myClass = interpreter.getClassLoader().loadClass("MyClass");
Method method = myClass.getDeclaredMethod("myMethod");
method.invoke(null);</code>

请注意,Beanshell 不再积极开发,但在生产环境中仍然可靠。

以上是如何执行存储在字符串变量中的Java代码?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn