Compiling classes with Toolprovider and loading them with ClassLoader
I'm开发者_运维技巧 trying to load classes that I generate an compile in runtime. I can compile them without no problem with this code:
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
List<File> sourceFileList = new ArrayList<File>();
sourceFileList.add(new File(sourceFile));
Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(sourceFileList);
CompilationTask task = compiler.getTask(null, fileManager, null, null,null, compilationUnits);
But I don't understand how to load the Class I've compiled (or where it is compiled) for posterior usage. I've tried several things like:
Class type = ClassLoader.getSystemClassLoader().loadClass(className);
or
ClassLoader loader = URLClassLoader.newInstance(new URL[] { myUrl }, getClass().getClassLoader()); //(URL?)
without success (I don't understand these...). Could you help me or give a simple example of ho to do this so I can develop form it?
Thanks in advance.
Your last attempt should work. myUrl
should refer to the directory (or Jar) containing the .class generated.
myUrl = new URL("file:///myGeneratedCode/");
The url must end with a "/"
to be considered a directory, otherwise, it will assume a Jar file.
I finally found the 'problem'. It was a stupid mistake from my side: I was trying to compile the generated java file before closing it. The annoying thing it's that JavaCompiler was not throwing any Exception.
With this solved and the class generated I have no more issues loading it with ClassLoader
Thanks again.
精彩评论