Java compiler of JDK 1.6: how to write class bytes directly into byte [] array?
So I recently learned about the new Java compiler API provided in JDK 1.6 This allows string to be compiled directly from the running code The class file becomes very simple:
String className = "Foo"; String sourceCode = "..."; JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); List<JavaSourceFromString> unitsToCompile = new ArrayList<JavaSourceFromString>() {{ add(new JavaSourceFromString(className,sourceCode)); }}; StandardJavaFileManager fileManager = compiler.getStandardFileManager(null,null,null); compiler.getTask(null,fileManager,unitsToCompile).call(); fileManager.close(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); FileInputStream fis = new FileInputStream(className + ".class"); IoUtils.copyStream(fis,bos); return bos.toByteArray();
You can get the source code of javasourcefromstring from Javadoc
This will make it very easy to compile sourcecode into foo. Code in the current working directory class.
My question is: can I compile directly into byte [] array and avoid the confusion of completely processing file I / O?
Solution
Maybe you can create your own javax tools. Javafilemanager implementation class, where you will return your own javax tools. Fileobject implementation, and then write it to memory instead of disk Therefore, for javax tools. Subclass of fileobject, writer openwriter() throws IOException method, and you will return Java io. StringWriter. All methods should be converted to their string counterparts