Mega Code Archive

 
Categories / Java Tutorial / Class Definition
 

The Class class also brings the possibility of creating an object without using the new keyword

The static forName method creates a Class object of the given class name. The newInstance method creates a new instance of a class. public class MainClass {   public static void main(String[] a) {     Class klass = null;     try {       klass = Class.forName("java.lang.String");     } catch (ClassNotFoundException e) {          }          if (klass != null) {       try {         // create an instance of the Test class         String test = (String) klass.newInstance();       } catch (IllegalAccessException e) {       } catch (InstantiationException e) {       }     }   } }