How can I compile classes in packages, to execute them later with “java Program” (without the package name)?

五迷三道 提交于 2019-12-06 03:28:09

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!