checking whether a package is existent or not

亡梦爱人 提交于 2019-12-29 06:48:40

问题


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


回答1:


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;
}



回答2:


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(...).




回答3:


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");
}


来源:https://stackoverflow.com/questions/2547867/checking-whether-a-package-is-existent-or-not

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!