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.
Package.getPackage(String name)
is the right tool for the job. Make sure you've
- Typed the name of the package correctly
- Try
Package.getPackages()
to see what's available - Make sure the classloaders match - test for instance
getClass().getPackage()
and thenPackage.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.
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:
- Load a class, or instantiate a class, from the package.
- Search the classpath, and check all jars/dirs in the classpath.
The 2nd option can fail if the code also is using url classloaders.
精彩评论