I am not really sure if I am using the right java terminology here, but here is what I want to do. I basically have some code working in a single directory. I want to reorganize them. Some previous threads suggested that pa开发者_Python百科ckage and import may be the answers. There were some missing details so I did not quite understand how the process work.
Here is my directory hiearchy.
/myDir/myProject
/myDir/myProject/common /mydir/myProject/feature1The feature1 requires stuff in common.
1) Do I compile the code in common and put it in a jar file or is there some other mechanism to build the package ?
2) Is there anything that I need to add to the actual *.java file to indicate it is a package ? 3) Where do I need to place this jar file ? 4) In feature1 files, how do I import the common code ? For example,import myDir.myProject.common.JARFILE; // will this work or do have to specify
// these actual componentYou can build all of your packages at once - they don't have to be in separate jar files. In your example, there are three packages, one for each directory in which you have source code. In the java file, you should add a line to indicate it's a package.
package myDir.myProject.common;
When you import, you should have a line for each class you wish to import. Like this:
import myDir.myProject.common.Class1; import myDir.myProject.common.Class2;
You can also use .*
to indicate all the classes in a package, but it's better to list out the specific classes if you can.
When you compile, you should compile from the root directory at the top of all the packages. This way, the root directory will have access to all of the source code files. For example, if you're looking for myDir.myProject.common.Class1
, the compiler will naturally look in myDir/myProject/common/
for Class1
. Notice that's a relative directory. Otherwise, if the package was already jarred up in a jar, it will find it there. If you have a package which you plan to use across multiple projects, jarring it up and referencing the directory that way can help with portability and version control.
The other suggestion I have is that you use an IDE like Eclipse which will handle many of these things for you. When I set up a project in Eclipse, I add a source directory, create packages, and then create classes within those packages. It handles all of the package and import statements in the code for me.
You can create a jar file of all required files and then add them to the classpath.
Or you can use
import myDir.myProject.common.*;
精彩评论