Package.getPackage deprecation
Stephen Colebourne
scolebourne at joda.org
Sun Aug 11 14:17:57 UTC 2024
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?
See also https://stackoverflow.com/questions/77259364/how-to-get-a-package-from-its-path-in-java
My current workaround is to call Package.getAllPackages() and search
for "java.util" manually, which appears to work OK.
thanks
Stephen
More information about the core-libs-dev
mailing list