how to run code compiled by JavaCompiler?

java, java-compiler-api, jsr199

Solution

You need to use reflection, something like that:

// 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);

Adapt it of course to suit your needs

Problem

Is there any way to run program compiled by JavaCompiler? [javax.tools.JavaCompiler] My code: ``` 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", " ")); } ``` Now i want to run that program with lifetime 1 sec and get output to string variable. Is there any way i could do that?

Original source