JDK6.0 introduces a new function of dynamic compilation, which allows you to dynamically write a class in the program and then compile it. After being compiled into a class file, you can load the dynamically compiled class into the memory by loading the class. Of course, it can also use the RunTime class to call the javac command for dynamic compilation.
The main steps of the dynamic compilation class are as follows:
① Write a string, which is the full content of the class to be compiled.
② Write the content of the string to the specified package under the project through the output stream.
③ Compile the created java file.
The classes involved in dynamic compilation include JavaCompiler and StandardJavaFileManager. For more information about how to compile these classes, see the following example.
4. Load the compiled bytecode into the memory and perform operations on it.
java.io.* String JAVA_SOURCE_FILE = "DynamicObject.java" String JAVA_CLASS_FILE = "DynamicObject.class" String JAVA_CLASS_NAME = "DynamicObject" main(String[] args) String tr = "\r\n" String source = "package com.compiler;" + tr + "public class "+JAVA_CLASS_NAME+ "{ " + tr + " public static void main(String[] args) {" + tr + " System.out.println(\"Hello World!\");" + tr + " } " + tr + "}" String fileName = System.getProperty("user.dir")+"\\src\\com\\compiler\\"+ FileWriter fw = FileWriter(fileName); PrintWriter pw = PrintWriter(fw); JavaCompiler compiler = StandardJavaFileManager fileManager = compiler.getStandardFileManager(, , Iterable sourcefiles = Iterable<String> options = Arrays.asList("-d", System.getProperty("user.dir")+"\\WebRoot\\WEB-INF\\classes" compiler.getTask(, fileManager, , options, URL[] urls = URL[] { URL("file:/"+System.getProperty("user.dir")+"/src" URLClassLoader loader = Class c = loader.loadClass("com.compiler."+ c.getMethod("main",String[].).invoke(, (Object) String[]{"a" } }