devxlogo

How to Create an Instance of a Class without a New Keyword

How to Create an Instance of a Class without a New Keyword

In the below program, pass any java class name into the method forName of the class java.lang.Class type. Cast it with your java class (in this example “AnyClass”) and get the instance in a reference of AnyClass. Using that reference you can call any method of AnyClass. Thus, you have created a instance without a new keyword.

 public class WithoutNew { public static void main(String s[]) {   try   {    AnyClass c=(AnyClass)Class.forName("AnyClass").newInstance();    c.AnyMethod();   }   catch(Exception e) { System.out.println(e); } }//end of main }//end of class

size=3>

devx-admin

Share the Post: