views:

69

answers:

3

How can i check whether a package like javax.servlet.* exists or not in my installation of java?

A: 

Java can only tell you if it can load a class. It can't tell you if a package exists or not because packages aren't loaded, only classes.

The only way would be by trying to load a class from that package. e.g., For javax.servlet.* you could do:

try {
    Class.forName("javax.servlet.Filter");
    return true;
} catch(Exception e) {
    return false;
}
noah
+2  A: 

Check if package is present as a resource:

// Null means the package is absent
getClass().getClassLoader().getResource("javax/servlet");

Alternatively, check if some class of this package can be loaded via Class.forName(...).

lexicore
A: 

If you look in the API docs for the installation you have, it will tell you all the installed packages, eg: http://java.sun.com/j2se/1.5.0/docs/api/

In code, you can do something like this:

Package foo = Package.getPackage("javax.servlet");

if(null != foo){
  foo.toString();
}else{
  System.out.println("Doesn't Exist");
}
Kylar
This works only if a class was loaded from that package before.
lexicore
This will only work if a class from that package has been loaded by the ClassLoader.
Rob Heiser
JINX! Buy me a coke! ;)
Rob Heiser
Wow, didn't know that. Thanks guys!
Kylar