Brief description
This class uses the JavaCompiler included with javax.tools.ToolProvider for compilation, uses IO File and NIO Files for corresponding path creation, reading and copying, and uses regular expressions to convert package names and directories. I just made a fault-tolerant integration of these things, and it has no technical content, so it is for convenience.
Module API
class DynamicReactor://empty parameter construct public Class<?> dynamicCompile(String srcPath);//Input a specified source file path, if compilation and copying are successful, return the corresponding Class class instance of the class private String changePacketToDic(String packageName);//Convert a legal package name to the path in the corresponding JavaClassPath (I am using eclipse, so I need to add the bin directory correspondingly. If you use other different compilers, please refer to the corresponding running context settings for appropriate modification) private String getPackage(String srcPath);//Try to get its package name from a legal Java file path
source code
import java.io.BufferedReader;import java.io.File;import java.io.FileReader;import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths;import java.nio.file.StandardCopyOption;import java.util.regex.Matcher;import java.util.regex.Pattern;import javax.tools.JavaCompiler;import javax.tools.ToolProvider;/** * DynamicReactor A dynamic compilation module is responsible for compiling source files, copying them to the corresponding packages and loading classes (JDK 1.7) * @author Three-way tiles* */public class DynamicReactor {JavaCompiler compiler;Pattern packagePattern;static final String regEx = "(?<=package//s).*(?=;);public DynamicReactor() {compiler = ToolProvider.getSystemJavaCompiler();packagePattern = Pattern.compile(regEx);}/** * Dynamic compiling the given source file* @param srcPath source file path * @return Class * <br>If successful returns the Class instance of the corresponding class* <br>If failure returns null * */public Class<?> dynamicCompile(String srcPath) {Class<?> result = null;//Get String packageName = getPackage(srcPath); if(packName == null) {System.out.println("DynamicRector:Load packageName Error!");return null;}//Call compiler to compile the specified source file int res = compiler.run(null, null, null,srcPath);if(res != 0) {System.out.println("DynamicRector:Compile Java Source Error!");return null;}//Get the path corresponding to the package name, create it if the path does not exist, and overwrite if the specified class file exists String packageDst = changePacketToDic(packName);File dstDir = new File(packageDst);if(!dstDir.exists()) {dstDir.mkdir();}Path pathFrom = Paths.get(srcPath.split("//.java")[0] + ".class");Path pathTo = Paths.get(packageDst,pathFrom.getFileName().toString());try {Files.move(pathFrom, pathTo, StandardCopyOption.REPLACE_EXISTING);}catch (IOException e) {System.out.println("DynamicRector:Move File Fail!");e.printStackTrace();}try {result = Class.forName(packName+"."+pathFrom.getFileName().toString().split("//.class")[0]);}catch (ClassNotFoundException e) {System.out.println("DynamicRector:Class Not found in Final!");}return result;}//This method converts a legal package name into the corresponding path private String changePacketToDic(String packageName) {String[] dirs = packageName.split("//.");String res = ".//bin";for (int i = 0;i < dirs.length;i++) {res += "//"+dirs[i];}return res;}//This method obtains the package name from the given path source file private String getPackage(String srcPath) {String result = null;BufferedReader br;try {br = new BufferedReader(new FileReader(srcPath));String data = br.readLine();while(data != null) {if(data.indexOf("package") != -1) {Matcher m = packagePattern.matcher(data);if(m.find()) {result = m.group();}break;}data = br.readLine();}br.close();}catch (IOException e) {System.out.println("DynamicRector:Error in open file "+srcPath);}return result;}}Summarize
The above is all the content of this article about dynamic compilation and loading of Java programming. I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!