How to run code compiled by JavaCompiler?

Is there a way to run a program compiled by JavaCompiler? [javax.tools.JavaCompiler]

My code is:

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 this program with a lifetime of 1 second and get the output in a string variable. Is there any way to do this?

+4
source share
2 answers

You need to use reflection, something like this:

 // 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.

+5
source

You must add the compiled class to the current class path.

There are several ways to do this, depending on how your project is configured. Here is 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 file system.

+1
source

Source: https://habr.com/ru/post/1299671/


All Articles