java 检查包是否存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2547867/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 21:43:46  来源:igfitidea点击:

checking whether a package is existent or not

javareflection

提问by abson

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

如何检查我的 java 安装中是否存在像 javax.servlet.* 这样的包?

回答by noah

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.

Java 只能告诉你它是否可以加载一个类。它不能告诉你一个包是否存在,因为没有加载包,只有类。

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

唯一的方法是尝试从该包中加载一个类。例如,对于 javax.servlet.* 你可以这样做:

try {
    Class.forName("javax.servlet.Filter");
    return true;
} catch(Exception e) {
    return false;
}

回答by lexicore

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

或者,检查这个包的某个类是否可以通过Class.forName(...).

回答by Kylar

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/

如果您查看已安装的 API 文档,它会告诉您所有已安装的软件包,例如: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");
}