Check for the availability of a package in Java


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"));
}

Updated on: 25-Jun-2020

454 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements