Is there a way to reference a package in java in code without using a String?
Let me explain myself:
I’ve a function that fetches all object contained in a package, but I’ve to reference that package using a String, lets say “com.google.guava”. This works, however, If I change the package name, the IDE is not able to automatically refractor the references, or if the package is external and dissapears after a major version change it is not detected at compile time.
With classes, I’d use a Class object directly when possible or Class#getName if what I need is a String representing the FQDN of the class, but I don’t know if there’s a way to do so with packages.
Sometimes I just do
Class<?> clazz = Foo.class; Package p = clazz.getPackage();
This is more a curiosity than a real issue, I usually just reference by String and write a junit test in order to detect nom-existant packages used this way
Advertisement
Answer
I can think of the following ways to get a Package
object:
Call
classLoader.getPackage(java.lang.String)
orPackage.getPackage(java.lang.String)
. These methods are deprecated.Call
Package classLoader.getDefinedPackage(java.lang.String)
Call
Package class.getPackage()
Call
Package[] Package.getPackages()
and then scan through the resulting array for the one that you want.
The last two approaches qualify as finding a Package
with using a String
.
There is no equivalent to a Java “class literal” (i.e. SomeClass.class
) for packages.