English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Summary
This class uses the JavaCompiler provided by javax.tools.ToolProvider for compilation, uses IO's File and NIO's Files for corresponding path creation, reading, and copying, uses regular expressions for package name and directory conversion. I just integrated these things with error tolerance, not much technical content, just for convenience.
Module API
class DynamicReactor://No-argument constructor public Class<?> dynamicCompile(String srcPath);//Input a specified source file path, if compiled and copied successfully, then return the Class instance corresponding to the class private String changePacketToDic(String packageName);//Converts a valid package name to the corresponding path in the JavaClassPath (I use eclipse, so I need to add the bin directory accordingly. If you use a different compiler, please refer to the corresponding runtime context settings for appropriate modifications) private String getPackage(String srcPath);//Attempts to obtain the package name from a valid 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 is a dynamic compilation module responsible for compiling source files, copying them to the corresponding package, and loading classes, etc. (JDK 1.7) * @author 三向板砖 * */ public class DynamicReactor { JavaCompiler compiler; Pattern packagePattern; static final String regEx = "(?<=package\\s).*(?=;)"; public DynamicReactor() { compiler = ToolProvider.getSystemJavaCompiler(); packagePattern = Pattern.compile(regEx); } /** * Dynamically compile the given source file * @param srcPath Source file path * @return Class * <br>Return the Class instance corresponding to the class if successful * <br>Return null if failed * */ public Class<?> dynamicCompile(String srcPath) { Class<?> result = null; //Obtain the source file at the given path String packName = getPackage(srcPath); if(packName == null) { System.out.println("DynamicRector: Load packageName Error!"); return null; } //Call the 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; } //Obtain the path corresponding to the package name, create the path if it does not exist, and overwrite the specified class file if it exists String packageDst = changePacketToDic(packName); File dstDir = new File(packageDst); if(!dstDir.exists()) { dstDir.mkdirs(); } Path pathFrom = Paths.get(srcPath.split("\.")[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("\.")[0]); } catch (ClassNotFoundException e) { System.out.println("DynamicRector:Class Not found in Final!"); } return result; } //This method converts a valid package name to 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 gets the package name from the source file at the given path. 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; } }
Summary
That's all about the sharing of dynamic compilation and loading code for java programming in this article. I hope it will be helpful to everyone. Those who are interested can continue to read other related topics on this site. Welcome to leave a message if there is any deficiency. Thank you for your support to this site!
Declaration: The content of this article is from the Internet, the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, does not edit the content artificially, and does not assume relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#w3Please report by email to codebox.com (replace # with @ when sending email) and provide relevant evidence. Once verified, this site will immediately delete the content suspected of infringement.