samedi 30 mai 2020

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 "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





Aucun commentaire:

Enregistrer un commentaire