首頁  >  文章  >  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