Check for the availability of a package in Java

Java 8Object Oriented ProgrammingProgramming

The availability can be checked using the method java.lang.Class.forName(). The class object associated with the class with the given string name can be returned using the method java.lang.Class.forName(String name, boolean initialize, ClassLoader loader), using the class loader that is used to load the class.

A program that demonstrates this is given as follows −

Example

 Live Demo

public class Main {
   public static void main(String args[]) {
      System.out.println(Availability("java.lang.String"));
   }
   public static boolean Availability(String name) {
      boolean flag = false;
      try {
         Class.forName(name, false, null);
         flag = true;
      }
      catch (ClassNotFoundException e) {
         flag = false;
      }
      return flag;
   }
}

Output

true

Now let us understand the above program.

A boolean variable flag stores the availability of java.lang.String in the method Availability(). A code snippet which demonstrates this is as follows −

boolean flag = false;
try {
   Class.forName(name, false, null);
   flag = true;
}
   catch (ClassNotFoundException e) {
   flag = false;
}
return flag;

In the method main(), the method Availability() is called and the value returned by it is printed. A code snippet which demonstrates this is as follows −

public static void main(String args[]) {
   System.out.println(Availability("java.lang.String"));
}
raja
Published on 09-Jan-2019 11:42:49
Advertisements