4

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?

Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
tzim
  • 1,715
  • 15
  • 37

2 Answers2

5

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
  • 562,542
  • 136
  • 1,062
  • 1,124
  • 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 Jan 28 '10 at 19:00
  • Securing an application such as that is a very good question, but it's also a very different question. – Kaleb Pederson Jan 28 '10 at 19:33
  • Where does `CLASS_OUTPUT` come from? –  Nov 22 '19 at 16:53
1

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
  • 2,870
  • 2
  • 24
  • 19