简体   繁体   中英

java.class files directory structure same as source files?

Currently i do some runitime compilation from a src file to a jar with following steps:

First: generate source files in a dir and subdirs

/main    
  /submain1
  /submain2 

Second: Compile code (currently all in .class files go into this directory)

 /builddir

Third: Generate jar from .class file into target folder

 /target

compilation is done by Java ToolProviders Javacompiler

ArrayList<File> files1 =  getSourceFiles();
Iterable<? extends JavaFileObject> compilationUnits1 = fileManager.getJavaFileObjectsFromFiles(files1);
JavaCompiler.CompilationTask task = compiler.getTask(null ,fileManager , null, optionList, null, compilationUnits1 );
boolean compiled = task.call();

Now my first question is, would it be better to separate all .class files into different compilation units and rebuild the same directory structure as the source files have?

And if so, how can it be done?

Java expects that foo.bar.MyClass is found at foo/bar/MyClass.class (with some additional classpath related requirements), otherwise you will get ClassNotFoundExceptions (or is it NoClassDefFoundErrors ) up the wazoo.

So not only should you have the same structure, you must have the same structure. I don't know why you're compiling like that instead of using an existing build tool which would generate correct results by default.

Creating a jar file is equivalent to creating a zip file, so just as a successful compilation doesn't mean that your program works, neither does having a jar file mean it would be a working one.

Now my first question is, would it be better to separate all .class files into different compilation units and rebuild the same directory structure as the source files have?

The output structure of the .class files must mirror the package names used in your source files. AFAIK folder structure of the source files does not matter that much.

If you use any other structure in your .jar file, classes cannot be found by the class loader.

So the answer to your question is no .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM