views:

230

answers:

2

Hi,

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 ?

Thx Tzim

+3  A: 

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

Pascal Thivent
But what about lifetime of a program? I used that in my web app. It's Spring based web application for learning java. If student make endless loop...
tzim
Securing an application such as that is a very good question, but it's also a very different question.
Kaleb Pederson
+1  A: 

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.

Quotidian