Why does Class.getPackage return the same Package for classes from different packages?

蓝咒 提交于 2019-12-04 06:08:53

The getPackage method is underspecified. Here's what bug 4256589 says about it:

ClassLoader.getPackage("foo") returns the package object defined for package foo in this particular class loader, or if this class loader didn't define package foo, the method returns what the parent class loader has defined for foo, if any.

To me, this says that the Package object returned by getPackage depends on whether the classloader "defined" a classes package itself, or if it found that package in its parent classloader. And the behavior are seeing seems to be consistent with this.

It is rather inconsistent. But does it really make any difference whether there is one package object or multiple package objects? Certainly, it shouldn't make any difference to type safety or to security ... unless you implemented some special package-based security scheme in a custom classloader or security manager.

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