Question

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?

Was it helpful?

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

OTHER TIPS

You have to add the compiled class to the current classpath.

There's a number of ways to do that, depending on how your project is set up. Here's one instance using java.net.URLClassLoader:

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

where "urls" is a list of urls pointing to the filesystem.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top