Package.getPackage deprecation
Alan Bateman
alan.bateman at oracle.com
Sun Aug 11 16:18:53 UTC 2024
On 11/08/2024 15:17, Stephen Colebourne wrote:
> I make use of Package.getPackage in Joda-Convert but the method has
> now been deprecated. I'd like to update my code, but AFAICT the
> suggested alternative does not work.
>
> The Joda-Convert code allows a user to convert a Package object to a
> String, and back again. Reading the deprecation, I'm aware that this
> may not work perfectly, but I do have to maintain compatibility as
> best I can.
>
> The deprecation asks users to use ClassLoader#getDefinedPackage
> instead. To do this properly, users have to loop up the ClassLoader
> parent list. However, the boot class loader is generally returned as
> null, and it is obviously impossible to call getDefinedPackage on a
> null reference.
>
> ie.
> Package.getPackage("java.util") works OK, but is deprecated
>
> The suggested replacement is this code, but it does not work because
> the boot class loader is returned as null:
> private static Package parsePackage(String str) {
> var loader = JDKStringConverter.class.getClassLoader();
> var pkg = (Package) null;
> while (loader != null && pkg == null) {
> pkg = loader.getDefinedPackage(str);
> loader = loader.getParent();
> }
> return pkg;
> }
>
> Am I misunderstanding things?
Package.getPackage is deprecated a long time, I don't think we've seen
too many complaints. Nowadays it's probably not too useful except to get
to package annotations (everything else in that API dates from JDK 1.2
and the since removed extension mechanism).
The set of package names for packages in the modules defined to the boot
loader can be obtained with code like this:
ModuleLayer.boot()
.modules()
.stream()
.filter(m -> m.getClassLoader() == null)
.flatMap(m -> m.getPackages().stream())
.collect(Collectors.toSet());
which I think is what you are looking for here.
-Alan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/core-libs-dev/attachments/20240811/e9e3ff4d/attachment.htm>
More information about the core-libs-dev
mailing list