简体   繁体   English

使用Java的默认程序包是不好的做法吗?

[英]Is the use of Java's default package a bad practice?

使用Java的默认程序包是不好的做法吗?

Yes, it is. 是的。 Ideally, package names should be globally unique, to avoid naming collisions. 理想情况下,程序包名称应该是全局唯一的,以避免命名冲突。 Using the default package breaks this convention. 使用默认程序包会违反此约定。 It's also impossible to import a class from the default package. 从默认包中导入类也是不可能的。

Why do unnamed packages exist at all, if it's such a bad idea? 如果这是一个坏主意,为什么根本不存在未命名的软件包? From the JLS §7.4.2 : 根据JLS§7.4.2

Unnamed packages are provided by the Java platform principally for convenience when developing small or temporary applications or when just beginning development. Java平台提供未命名的软件包主要是为了在开发小型或临时应用程序或刚开始开发时提供方便。

There are problems on many different levels: 在许多不同层面上都有问题:

  • you can't import classes in the default package from classes that are not 您不能从非默认类中导入默认包中的类
  • you will get class loading problems if you try to resolve the default package in multiple artifacts 如果尝试在多个工件中解析默认包,则会遇到类加载问题
  • you can no longer use the default and protected scope like you normally can 您将无法再像通常那样使用默认的受保护范围
  • there's no obvious distinction between your code and other code 您的代码和其他代码之间没有明显的区别

Yes it is. 是的。 As other answers have stated, you can't load classes from the default package. 正如其他答案所述,您无法从默认包中加载类。

See SO answers: 看到这样的答案:

How to import a class from default package 如何从默认包中导入类
How to access java-classes in the default-package? 如何访问默认包中的java类?

However, log4j requires that the configuration be located in the default package. 但是,log4j要求配置位于默认软件包中。 This is the only thing that's reasonable to keep there. 这是唯一合理的做法。

Edit: As Sean Patrick Floyd and Michael have pointed out in the comments, you can put any configuration files into the default package. 编辑:正如Sean Patrick Floyd和Michael在评论中指出的那样,您可以将任何配置文件放入默认包中。 Thanks to both of you for pointing this out to me. 感谢你们两个向我指出这一点。

Yes, it is. 是的。 The problem is that it is not possible to import classes from the default package. 问题在于无法从默认包中导入类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM