.java文件中的包使得类文件不可用 [英] package in .java file makes class file unuseable
问题描述
自从我上次完成Java以来已经太久了,我不记得为什么会发生以下情况:
It's been too long since I've last done Java, and I can't remember why the following happens:
鉴于此文件,由标准Maven创建项目,如下所示: Maven教程
Given this file, created by a standard Maven project, as can be seen here: Maven Tutorial
package com.mycompany.app;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
}
}
编译这个,甚至不是Maven,而是标准javac可执行文件,将生成一个没有错误的类文件。尝试运行类文件,你会收到这个错误:
Compiling this, not even with Maven but with the standard javac executable, will generate a class file without errors. Try to run the class file, and you get this error:
Exception in thread "main" java.lang.NoClassDefFoundError: App (wrong name: com/mycompany/app/App)
删除包命令,再次编译它运行得很好。为什么是这样?我正在运行JDK 1.6.0_21 btw。
Remove the package command, compile again and it runs just fine. Why is this? I'm running JDK 1.6.0_21 btw.
推荐答案
创建包是创建嵌套子目录来表示类的包层次结构。在您的情况下,包名称是com.mycompany.app,因此 App.class
(已编译的App.java文件)应驻留在com / mycompany / app子-目录。但是源文件驻留在哪里并不重要。例如,我复制了您的文件并执行了以下操作:
One thing you must do after creating a package for the class is to create nested subdirectories to represent package hierachy of the class. In your case the package name is "com.mycompany.app" so the App.class
(compiled App.java file) should reside in "com/mycompany/app" sub-directory. It doesn't matter where the source file is residing though. For example, I have copied your file and did the following:
$ ls
App.java
$ javac App.java
$ ls
App.class App.java
$ mkdir -p com/mycompany/app
$ mv App.class com/mycompany/app/
$ java com.mycompany.app.App
Hello World!
$
请阅读关于Java包的Wikipedia页面以获取更多信息。您还可以查看以下链接:
Please read Wikipedia page about Java Packages for more information. You can also take a look at these links:
- The Java packages tutorial
- Java packages tutorial
- Oracle's notes on packages
祝你好运!
这篇关于.java文件中的包使得类文件不可用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!