我如何编译包中的类,以便稍后使用“java程序"执行它们?(没有包名)? [英] How can I compile classes in packages, to execute them later with "java Program" (without the package name)?

查看:28
本文介绍了我如何编译包中的类,以便稍后使用“java程序"执行它们?(没有包名)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于 Java 中的 javac 和包的快速问题.

I have a quick question regarding javac and packages in Java.

我有一个简单的程序(我们称之为 Program.java),它当前位于以下目录中:

I have a simple program (we'll call it Program.java) which is currently in the following directory:

  • myRepository/myProgram

在 myRepository/myProgram 目录中的 Program.java 和其他 .java 文件中,我已经声明了 package myProgram.* 并且还包含了 import myProgram.*;.

In Program.java and other .java files in the myRepository/myProgram directory, I have declared package myProgram.* and also included import myProgram.*;.

因此,当我输入 javac myProgram/Program.java 时,它编译良好,如果我输入 java myProgram/Program,它运行良好.

So when I type javac myProgram/Program.java, it compiles fine and it runs fine if I type java myProgram/Program.

但是,我试图在 myRepository 目录中生成 .class 文件,而不是 myRepository/myProgram,这是源文件所在的目录.我尝试了 javac myProgram/Program.java -d .. 它在 myRepository 目录中生成 .class 文件,但是当我尝试java 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:

线程main"中的异常java.lang.NoClassDefFoundError:程序(错误名称:myProgram/Program).

Exception in thread "main" java.lang.NoClassDefFoundError: Program (wrong name: myProgram/Program).

有什么办法可以让 .class 文件显示在主目录 (myRepository) 而不是源代码所在的位置 (myRepository/myProgram) 并且能够执行 java Program在 myRepository 中?

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?

推荐答案

您最好将源代码放在目录 source/myProgram 并创建一个名为 build 的目录来放置 .class 文件.因此,您可以这样编译和运行:

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

这篇关于我如何编译包中的类,以便稍后使用“java程序"执行它们?(没有包名)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆