mP.
mP.

Reputation: 18266

Java: Testing if a package (using its name) is present...

I would like to test if a particular package is known to the current classloader or system. Package.getPackage(String name) seems to return null thus im stuck. ClassLoader does not contain any method that does the same thus im stuck...

I d rather not load a class in the package to test if it is present, surely theres a better way.

Any pointers would be appreciated.

Upvotes: 3

Views: 279

Answers (2)

Kaj
Kaj

Reputation: 10949

There's no easy way to get information on if a package exist, unless a class has been loaded from that package. Package.getPackage does only work if a class from the named package has been loaded.

Your options are:

  1. Load a class, or instantiate a class, from the package.
  2. Search the classpath, and check all jars/dirs in the classpath.

The 2nd option can fail if the code also is using url classloaders.

Upvotes: 1

Aleksi Yrttiaho
Aleksi Yrttiaho

Reputation: 8446

Package.getPackage(String name) is the right tool for the job. Make sure you've

  1. Typed the name of the package correctly
  2. Try Package.getPackages() to see what's available
  3. Make sure the classloaders match - test for instance getClass().getPackage() and then Package.getPackage(String name)

The method searches for the package in the current classloader only (or System classloader if current classloader is null). If no class in the package is loaded in the current classloader the package will no be present.

Upvotes: 4

Related Questions