Skip to content

Referencing packages in java without using String

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 “”. 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



I can think of the following ways to get a Package object:

  1. Call classLoader.getPackage(java.lang.String) or Package.getPackage(java.lang.String). These methods are deprecated.

  2. Call Package classLoader.getDefinedPackage(java.lang.String)

  3. Call Package class.getPackage()

  4. 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.

5 People found this is helpful