質問

JavaCompilerでコンパイルされたプログラムを実行する方法はありますか? 【javax.tools.JavaCompiler

私のコード:

JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    CompilationTask task = compiler.getTask(null, null, diagnostics, null, null, prepareFile(nazwa, content));
    task.call();

    List<String> returnErrors = new ArrayList<String>();
    String tmp = new String();
    for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
        tmp = String.valueOf(diagnostic.getLineNumber());
        tmp += " msg: "+ diagnostic.getMessage(null);
        returnErrors.add(tmp.replaceAll("\n", " "));
    }

今私は、生涯1秒でそのプログラムを実行して、文字列変数への出力を取得したいです。私はそれを行うことができます方法はありますか?

役に立ちましたか?

解決

あなたは、リフレクションを使用するためにそのような何かを必要とします

// Obtain a class loader for the compiled classes
ClassLoader cl = fileManager.getClassLoader(CLASS_OUTPUT);
// Load the compiled class
Class compiledClass = cl.loadClass(CLASS_NAME);
// Find the eval method
Method myMethod = compiledClass.getMethod("myMethod");
// Invoke it
return myMethod.invoke(null);

あなたのニーズに合うように、もちろん、それを適応させます

他のヒント

あなたは現在のクラスパスにコンパイルされたクラスを追加する必要があります。

は、プロジェクトの設定方法に応じて、それを行うにはいくつかの方法があります。ここでjava.net.URLClassLoaderを使用して1件のインスタンスがあります:

ClassLoader cl_old = Thread.currentThread().getContextClassLoader();
ClassLoader cl_new = new URLClassLoader(urls.toArray(new URL[0]), cl_old);

ここで、「URLの」ファイルシステムを指すURLのリストです。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top