12

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

Kylar
  • 8,876
  • 8
  • 41
  • 75
abson
  • 9,148
  • 17
  • 50
  • 69

3 Answers3

14

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(ClassNotFoundException e) {
    return false;
}
yegor256
  • 102,010
  • 123
  • 446
  • 597
noah
  • 21,289
  • 17
  • 64
  • 88
12

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
  • 42,748
  • 17
  • 132
  • 221
  • 1
    Note that this does not work for JDK 9+, where packages are encapsulated in modules. However, classes are not encapsulated, so the following works: `getClass().getClassLoader().getResource("java/lang/String.class")` – gjoranv Jul 16 '19 at 22:58
5

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
  • 8,876
  • 8
  • 41
  • 75