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
Foo.class.getPackage()is already the best you can get. But “all object contained in a package” makes no sense. A package contains classes, not objects.Packageobject, as the classPackagedoes not offer anything for resource lookup. ThePackageclass only exists to allow accessing meta information. Resources have to be accessed viaFoo.class.getResource(…)anyway. The standard way to iterate over all resources, is to open a filesystem.