How can i check whether a package like javax.servlet.* exists or not in my installation of java?
Asked
Active
Viewed 1.5k times
12
-
2Easy way : Import the package, use it, compile. – Tom Mar 30 '10 at 19:02
3 Answers
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;
}
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
-
1Note 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
-
5
-
This will only work if a class from that package has been loaded by the ClassLoader. – Rob Heiser Mar 30 '10 at 19:11