checking whether a package is existent or not

前端 未结 3 1729
逝去的感伤
逝去的感伤 2020-12-17 17:46

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

相关标签:
3条回答
  • 2020-12-17 18:28

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

    0 讨论(0)
  • 2020-12-17 18:31

    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;
    }
    
    0 讨论(0)
  • 2020-12-17 18:40

    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");
    }
    
    0 讨论(0)
提交回复
热议问题