开发者

does java package affect runtime behavior?

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 {
开发者_如何学C        // 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


Short: Yes

Longer: You really need to set the working directory to the folder where the folder a
(which contains b) is in. Otherwise it will give errors as you asked.


My Edit after your Edit:
You need to create the packages yourself, by creating folders of course. And put in that package the source file you want to compile.

 File sourceFile = new File(root, "a\\b\\c\\Test.java");
 sourceFile.getParent().mkdirs();
 FileWriter fw = new FileWriter(sourceFile);
 fw.write(source);
 fw.flush();
 fw.close();

 ....

If you try to compile Java source code, which isn't in the correct package, it won't work and you should get a compilation error. I have to admit that I never compiled source code this way.


As you know when you try to load a.b.c it will looking a directory a/b for a file c so 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜