/** * Required JDK >= 1.6<br><br> * This class can help you create the Java byte code dynamically through the string and load it into memory.<br><br> * <p> * HOW TO:<br> * First step. <code>Map<String, byte[]> bytecode = DynamicLoader.compile("TestClass.java", javaSrc);</code><br> * Second step. <code>DynamicLoader.MemoryClassLoader classLoader = new DynamicLoader.MemoryClassLoader(bytecode);</code><br> * Third step. <code>Class clazz = classLoader.loadClass("TestClass");</code><br> * <br> * Then just like the normal use of the call this class can be. * * @author https://github.com/Lua12138/UtilsClass/blob/master/locals/DynamicLoader.java */ publicclassDynamicLoader{ /** * auto fill in the java-name with code, return null if cannot find the public class * * @param javaSrc source code string * @return return the Map, the KEY means ClassName, the VALUE means bytecode. */ publicstatic Map<String, byte[]> compile(String javaSrc) { Pattern pattern = Pattern.compile("public\\s+class\\s+(\\w+)");
Matcher matcher = pattern.matcher(javaSrc);
if (matcher.find()) return compile(matcher.group(1) + ".java", javaSrc); returnnull; }
/** * @param javaName the name of your public class,eg: <code>TestClass.java</code> * @param javaSrc source code string * @return return the Map, the KEY means ClassName, the VALUE means bytecode. */ publicstatic Map<String, byte[]> compile(String javaName, String javaSrc) { JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager stdManager = compiler.getStandardFileManager(null, null, null);
publicMemoryJavaFileManager(JavaFileManager fileManager){ super(fileManager); classBytes = new HashMap<String, byte[]>(); }
public Map<String, byte[]> getClassBytes() { return classBytes; }
publicvoidclose()throws IOException { classBytes = new HashMap<String, byte[]>(); }
publicvoidflush()throws IOException { }
/** * A file object used to represent Java source coming from a string. */ privatestaticclassStringInputBufferextendsSimpleJavaFileObject{ final String code;
public CharBuffer getCharContent(boolean ignoreEncodingErrors){ return CharBuffer.wrap(code); }
public Reader openReader(){ returnnew StringReader(code); } }
/** * A file object that stores Java bytecode into the classBytes map. */ privateclassClassOutputBufferextendsSimpleJavaFileObject{ private String name;