Downloading external source code and using it internally (by recompiling or something else)

Is there a way to use the external source code and load it into a Java program so that it can be used by it?

I would like to have a program that can be changed without editing the full source code and that it is even possible without compiling it every time. Another advantage is that I can change parts of the code as I want.

Of course, I must have interfaces so that I can send data to this and return to the original program again.

And, of course, this should be faster than a pure system of interpretation.

So, is there a way to do this, as an additional compilation of these parts of the external source code and the start of the program after that?

Thanks in advance, Andreas :)

+3
source share
3 answers

For this you need the javax.tools API . So you need to install at least the JDK to make it work (and let your IDE point to it instead of the JRE). Here is an example of a basic launch (without proper exception handling and coding, to make the main example less opaque, coughing):

public static void main(String... args) throws Exception {
    String source = "public class Test { static { System.out.println(\"test\"); } }";

    File root = new File("/test");
    File sourceFile = new File(root, "Test.java");
    Writer writer = new FileWriter(sourceFile);
    writer.write(source);
    writer.close();

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    compiler.run(null, null, null, sourceFile.getPath());

    URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { root.toURI().toURL() });
    Class<?> cls = Class.forName("Test", true, classLoader);
}

test stdout, . , , . API /.

+9

Java 6 javax.tools. ToolProvider.getSystemJavaCompiler() javax.tools.JavaCompiler, . Java, com.sun.tools.javac.Main, .

+1

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


All Articles