Oliver
Oliver

Reputation: 4173

How to access package via Package.getPackage(...)?

In my current project I would like to store some configuration data in a package annotation and to access it by some CDI producers. If the annotation is not found in the current package the producers will search for it upward in the package hierarchy.

So far so good. Unfortunately it seems so that I can access an existing package via Package.getPackage("my.package") only after the first access to one of its classes or interfaces.

The following example illustrates this behaviour:

Class in package a.b

package a.b;

public class ClassInMitte {
}

Example programm to access the package oben.mitte

package other;

public class Refl {
    public static void main(String[] args)
    {
        Package viaName = Package.getPackage("a.b");

        System.out.println(viaName.getName());
        System.out.println(viaName.hashCode());
    }
}

Running Refl results in a NullPointerException. But if I add new ClassInMitte() as first statement I can access the package information. Somehow I must access the content of a package before I can access the package information itself. This makes sense since otherwise the classloaders must scan the whole classpath while starting.

But netherless is there an easy way to access package information without accessing the content of the package before? I know I could use frameworks like reflections but a 'lightweight' solution would be my prefered solution.

Upvotes: 0

Views: 250

Answers (1)

Joni
Joni

Reputation: 111219

Package.getPackage only returns packages that are already known to the current class loader, and the only way to do that is by loading a class from that package. It's basically a wrapper for ClassLoader.getPackage.

Upvotes: 1

Related Questions