Detect if a package is available

From CodeCodex

Java[edit]


public class ClassUtils {

  public static void  main(String args[]) {
    System.out.println ("Swing " +
       (ClassUtils.isAvailable("javax.swing.JComponent")?"present":"absent"));
    System.out.println ("JAI " +
       (ClassUtils.isAvailable("javax.media.jai.ImageJAI")?"present":"absent"));
    System.out.println ("SAX " +
       (ClassUtils.isAvailable("org.xml.sax.XMLReader")?"present":"absent"));
    System.out.println ("ImaginaryClass " +
       (ClassUtils.isAvailable("imaginary.ImaginaryClass")?"present":"absent"));
    System.out.println ("Java3d " +
       (ClassUtils.isJava3dAvailable()?"present":"absent"));
    /*
    output :
        Swing present
        JAI absent
        SAX present
        ImaginaryClass absent
        Java3d absent
    */    
  }

  public static boolean isAvailable(String className) {
    boolean isFound = false;
    try {
       Class.forName(className, false, null);
       isFound = true;
    }
    catch (ClassNotFoundException e) {
       isFound = false;
    }
    return isFound;
  }

  public static boolean isJava3dAvailable() {
   return isAvailable("javax.media.j3d.View");
  }
}