if I define a java class in package a.b.c, but I just put the compiled class file in c:\
, and using a URLClassloader to load it, will there be errors ?
Edit———————————————————-
package amarsoft.rcp.base.util.test;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
public class JavaCompolierDemo {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String source = " package a.b.c; public class Test { public static void main(String args[]) { System.out.println(\"hello\"); } }";
// Save source in .java file.
File root = new File("C:\\java\\");
root.mkdir();
File sourceFile = new File(root, "\\Test.java");
Writer writer = new FileWriter(sourceFile);
writer.write(source);
writer.close();
// Compile source file.
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
compiler.run(null, null, null, sourceFile.getPath());
}
}
when I run above code, the defined package a.b.c will not be generated as directory a\b\c, the Test.class will be in c:\Test.class
As you know when you try to load
a.b.cit will looking a directorya/bfor a filecso if the file is not there, it won’t find it.If you change the URLClassLoader to look for the file in another directory, it can load the class without error.
What are you trying to do?
EDIT: Here is an example for a small compiler library I wrote a few years ago. It takes the source from a String in memory and gives you the outer class compiled.
http://essence.svn.sourceforge.net/viewvc/essence/trunk/essence-file/src/test/java/org/freshvanilla/compile/CompilerTest.java?revision=293&view=markup
This uses the Compiler API to do this. If you want to debug the code it will write it to a directory you specify (so you can step through the generated code) otherwise it works entirely in memory.