How to make Object of a class By Reflection API

Points To Remember
  • Reflection API is a powerful technique to find out environment of a class as well as to inspect the class itself.
  • Reflection API was introduced in Java v1.1
  • It allows user to get full information about the classes, interfaces, constructors, methods, variables etc.
  • It is available in java.lang.reflect package.
Example : Creating Object Using Reflection API
In the example below we are trying to create the object of class "A" in class "Test" using reflection api. We will first get the class of "A" by using .class and then call the newInstance() method to get the object of this class.
class A{

  public A(){
    System.out.println("class A constructor");
  }

  public void show(){
    System.out.println("class A show() ");
  }
  public void show(String s){
    System.out.println(s);
  }
}

public class Test{
    
   public static void main(String args[]){
     try{

       Class clazz = A.class;
       A object = (A)clazz.newInstance();
       object.show();
       object.show("class A show(String)");

     }catch(Exception e){
       System.out.println("Error");

     }
}

}
class A constructor
class A show() 
class A show(String)
Example : Creating Object Using Class.forName()
In this example we will create the object of a class using Class.forName("").newInstance(). This will give us an object of the class we specify in .forName().
class A{

  public A(){
    System.out.println("class A constructor");
  }

  public void show(){
    System.out.println("class A show() ");
  }
  public void show(String s){
    System.out.println(s);
  }
}

public class Test{
    
   public static void main(String args[]){
     try{
       A object = (A)Class.forName("A").newInstance();
       object.show();
       object.show("class A show(String)");

     }catch(Exception e){
       System.out.println("Error");

     }
}

}
class A constructor
class A show() 
class A show(String)

No comments:

Powered by Blogger.