独立程序包

Package for standalone program

我是 Java 的新手,我知道包的作用。您可以使用它们将 Java 应用程序的多个文件一起排序。但是,如果您的应用程序只有一个 class,将它放在一个包中是标准的吗?这样做的利弊是什么?

编辑:之后我将这个 class 打包成一个 .jar 文件。

oracle documentation可以看出

The primary motivation for jar development was so that Java applets and their requisite components (.class files, images and sounds) can be downloaded to a browser in a single HTTP transaction, rather than opening a new connection for each piece. This greatly improves the speed with which an applet can be loaded onto a web page and begin functioning. The JAR format also supports compression, which reduces the size of the file and improves download time still further. Additionally, individual entries in a JAR file may be digitally signed by the applet author to authenticate their origin.

来自 Package Documentation of Oracle,

For small programs and casual development, a package can be unnamed (§7.4.2) or have a simple name, but if code is to be widely distributed, unique package names should be chosen using qualified names. This can prevent the conflicts that would otherwise occur if two development groups happened to pick the same package name and these packages were later to be used in a single program.

如果它只有一个 class 并且没有任何依赖项或资源文件,则它可能是非生产应用程序。因此,如何启动您的应用程序完全取决于您。

如果您想分发您的应用程序 - 使其符合标准,将其放入 jar 中,发布到 maven...

Java class加载程序通过连接包和 class 名称来识别您的 classes。所以,如果你不使用包,名称冲突的可能性会更高。即使您的应用仅包含一个 class,您仍将引用许多其他应用,无论是否明确。

还要考虑到您只能用一个 class 构建非常普通的应用程序,所以这种情况可能不会永远持续下去。

除此之外,class 没有包是一种边界情况,因此您可能会发现许多工具无法使用它。(我在 Eclipse 的 Web 服务构建器工具中遇到了这个问题).

总之,用一个包。它不会给您带来任何麻烦,并且(至少可能)会为您节省很多。

这实际上取决于您的编译方式和 运行 程序,但最终是 您的选择

让我们看一下您可以构建程序的一些不同方式。

1。使用 javac

编译文件

如果您使用 javac 编译文件,则包无关紧要。它将在与源文件 相同的目录 中生成 .class 文件。

2。编译为 JAR 文件

如果您正在编译为 JAR 文件,那么 .class 文件将位于您的包名称中指定的目录中。虽然这 不会影响程序 运行.

在这两种情况下,我会说 包标识符对于单文件程序来说是不必要的。但是,有一个例外。

异常...

如果您计划在更大的程序class中使用,那么添加相关的包名称将是必不可少的。

这是因为它会...

  1. 防止 名称冲突 当默认包中的其他 class 名称相同时。

  2. 帮助人们了解您的class是否他们想要的

您能想象如果 20 个不同的开发人员在默认包中制作了一个 List class,并且不知何故他们都在一个项目中结束了吗?那将是混乱!我该如何选择合适的List?

所以在写一个class别人会在自己的项目中使用的情况下,你应该绝对使用包名。