How can I compile classes in packages, to execute them later with "java Program" (without the package name)?
I have a quick question regarding javac and packages in Java.
I have a simple program (we'll call it Program.java) which is开发者_高级运维 currently in the following directory:
- myRepository/myProgram
In Program.java and other .java files in the myRepository/myProgram directory, I have declared package myProgram.*
and also included import myProgram.*;
.
So when I type javac myProgram/Program.java
, it compiles fine and it runs fine if I type java myProgram/Program
.
However, I'm trying to get the .class files to be produced in the myRepository
directory, not myRepository/myProgram
, which is where the source files are. I tried javac myProgram/Program.java -d ..
which produces the .class files in myRepository directory, but when I try "java Program", it gives me the following error:
Exception in thread "main" java.lang.NoClassDefFoundError: Program (wrong name: myProgram/Program).
Is there any way way I could get .class files to show up in the main directory (myRepository) instead of where the source codes are (myRepository/myProgram) and be able to execute java Program
while inside myRepository?
You better put the source codes on the directory source/myProgram and create a directory called build to put the .class files. Thus, you can compile and run this way:
javac source/myProgram/Program.java -d build
cd build
java myProgram/Program
Packaged classes can not be stored in any directory. This link could be helpful: http://www.herongyang.com/Java-Tools/javac-Option-d-Specifying-Output-Directory.html
You should call the compiler from the myRepository
directory, not from inside the package directory, like this: javac myProgram/Program.java
, and then java myProgram.Program
.
The created classes have to be in a package-structure for the classloader to find them (at least with the default classloader).
You can put them in another directory, but then they will have the right structure there, and you should give this directory to your VM:
javac -d ../classes myProgram/Program.java
java -cp ../classes myProgram.Program
There is no way (with the default java
command) to execute a class in a package without mentioning the package name.
You could use a wrapping class which is in the anonymous package (e.g. without any package
declaration), which simply calls the original class:
class Program {
public static void main(String[] args) {
// delegate to real main class and method:
myProgram.Program.main(args);
}
}
Alternatively, if you are developing with an IDE, you can often simply start your program with a button click.
For distribution, you would instead put all your class files in a jar file and define the main class in the manifest. Then you can call your program this way:
java -jar myProgram.jar
精彩评论