Check if package exists at runtime

Discussion in 'Java' started by Bruce Lee, Jan 27, 2006.

  1. Bruce Lee

    Bruce Lee Guest

    Is there anyway to check if a package exists at runtime? Class is simple -

    try{
    Class.forName("java.class1.Class12");
    }catch(Exception e){}

    but can you do this for a whole package?
     
    Bruce Lee, Jan 27, 2006
    #1
    1. Advertising

  2. Bruce Lee wrote:
    > Is there anyway to check if a package exists at runtime? Class is simple -
    >
    > try{
    > Class.forName("java.class1.Class12");
    > }catch(Exception e){}
    >
    > but can you do this for a whole package?


    Package.getPackages() gets all packages known to the callers
    ClassLoader. At least this is what the documentation says...
     
    Damian Brunold, Jan 27, 2006
    #2
    1. Advertising

  3. Damian Brunold wrote:
    > Bruce Lee wrote:
    >> Is there anyway to check if a package exists at runtime? Class is
    >> simple -
    >>
    >> try{
    >> Class.forName("java.class1.Class12");
    >> }catch(Exception e){}
    >>
    >> but can you do this for a whole package?

    >
    > Package.getPackages() gets all packages known to the callers
    > ClassLoader. At least this is what the documentation says...


    public static boolean packageExists(String name) {
    return Package.getPackage(name)!=null;
    }

    http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Package.html#getPackage(java.lang.String)

    robert
     
    Robert Klemme, Jan 27, 2006
    #3
  4. You can, if the package is sealed, just check if all classes can be
    retrieved by Class.forName(). Otherwise, the notion of "whole package"
    makes no sense, since there may be any number of classes also living in
    that package you have never heared about.
     
    Stefan Schulz, Jan 27, 2006
    #4
  5. Bruce Lee

    Chris Smith Guest

    Robert Klemme <> wrote:
    > public static boolean packageExists(String name) {
    > return Package.getPackage(name)!=null;
    > }


    Note that this will return true ONLY when a class from the package has
    already been loaded. It does not somehow check if anything from the
    package might be available in the future. That is the JVM's definition
    of whether the package exists (it doesn't exist until it's first used),
    but it's probably not the definition the OP wanted.

    --
    www.designacourse.com
    The Easiest Way To Train Anyone... Anywhere.

    Chris Smith - Lead Software Developer/Technical Trainer
    MindIQ Corporation
     
    Chris Smith, Jan 27, 2006
    #5
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.

Share This Page