Monday, October 22, 2012

Reflection API : A Brief Introduction


Reflection API is a powerful technique (that provides the facility) to find-out its environment as well as to inspect the class itself. Reflection API was included in Java 1.1. The classes of Reflection API are the part of the package java.lang.reflect and the methods of Reflection API are the parts of the package java.lang.class. It allows the user to get the complete information about interfaces, classes, constructors, fields and  various methods being used. It also provides an easy way to create a Java Application that was not possible before Java 1.1. You can create methods like event handlers, hash code etc and also find-out the objects and classes.

With the help of Reflection API you can get the information about any class of the java.lang package. There are some useful methods like getName() and getInterfaces(), which allows us to retrieve the name of the class and the interfaces of the package respectively.

Avoid using Reflection API in those applications wherever it affects the application's performance, security related code of the application such as in Applet programming. Reflection API also affects the application if the private fields and methods are there.

Here we are providing few of the examples to give a better overview of the Reflection API :

1.    Getting the implemented Interfaces
In this section you will learn how to retrieve an Interface (that included in the program) by using the getInterfaces() method. Here is an example that provides the usage of the getInterfaces() method in more detail.

2.    Retrieving the class name through Reflection API
A more generic way, how to retrieve the name of the class (that is used in the program) that reflects the package name by using the getName() method. Here is an example that provides the proper way to use the getName() method.

3.    Finding out the superclass name of the Class
Here we show you the way to find out the Superclass name by using the getSuperclass() method. The given example demonstrates the use of getSuperclass() method in more detail.

4.    Getting the method name used in the Application
In this section we describe how to retrieve method name by using the getMethods() method. Here is an example that demonstrates the use of the getMethods() method in more detail.

5.    Finding out the object of the Class
This section illustrates how to retrieve an object name that reflects the package name by using the object.getClass() method. Here is an example that provides the proper usage of theobject.getClass() method in more detail.

6.    Finding out the class fields
This section explores you, how to retrieve the fields of the class by using the getFields() method. For this we are taking an example that provides the use of the getFields() method in detailed way.

7.    Getting information about Constructor
In this section you will learn, how to retrieve the information about the constructor by using the getConstructors() method. Here is an example that provides the usage of the getConstructors() method.

 Getting the implemented Interfaces

In this section you will learn how to retrieve an Interface (that included in the program) by using the getInterfaces() method. Here is an example that provides the usage of the getInterfaces() method in more detail.

Create an object of class Finterface and assign it with java.util.Integer.class.. Now retrieve Interfaces (included in the program) and store their references in an array of class Class by using the getInterfaces() method.

Finterface.java:  
import java.lang.reflect.*;

public class Finterface {
  public static void main(String str[]) {
    Class cls = java.util.List.class;
    Class[] intfs = cls.getInterfaces();
    int len = intfs.length;
    for(int i = 0; i < len; i++) {
      System.out.println(intfs[i]);
    }

  }
}

Here is the output of this Example :

C:\vignesh>javac Finterface.java

C:\vignesh>java Finterface
interface java.util.Collection

Retrieving the class name through Reflection API

A more generic way, how to retrieve the name of the class (that is used in the program) that reflects the package name by using the getName() method. Here is an example that provides the proper way to use the getName() method.
Here we create an object of class Fclass and assign the reference of the class java.util.Integer.class to it. Now retrieve the class name (that is included in the program) by using the getName() method.

 Fclass.java
import java.lang.reflect.*;

public class Fclass {
  public static void main(String[] args) {
    Class cls = java.lang.Integer.class;
    String info;
    info = cls.getName(); // It will show java.lang.Integer
    System.out.println(info);
  }
}

Here is the output of the Example :

C:\vignesh>javac Fclass.java

C:\vignesh>java Fclass
java.lang.Integer

 Finding out the super class name of the class

 Here we show you the way to find out the Superclass name by using the getSuperclass() method. The given example demonstrates the use of getSuperclass() method in more detail.

Create a class "Fsupercls". Populate it with the Checkbox objects. Now retrieve the Superclass name by using the getSuperclass() method.

Fsupercls.java: 
import java.lang.reflect.*;
import java.awt.*;

public class Fsupercls {
  public static void main(String[] args) {
    Checkbox big = new Checkbox();
    printName(big);
  }

  static void printName(Object objct) {
    Class cls = objct.getClass();
    Class sup = cls.getSuperclass();
    System.out.println(sup);
  }
}

Here is the output of the Example :

C:\vignesh>javac Fsupercls.java

C:\vignesh>java Fsupercls
class java.awt.Component

Getting the method name used in the Application

In this section we describe how to retrieve method name by using the getMethods() method. Here is an example that demonstrates the use of the getMethods() method in more detail.

Define a class named "Fmethod" and then create an object of this class and get the reference of java.util.Integer.class into it.Now retrieve the method name by using the getMethods() method.

Fmethod.java:  
import java.lang.reflect.*;

public class Fmethod {
  public static void main(String[] args) {
    Class cls = java.lang.Integer.class;
    Method method = cls.getMethods()[0];
    String info;
    info = method.getName();
    System.out.println(info);
  }
}

Here is the output of the Example :

C:\vignesh>javac Fmethod.java

C:\vignesh>java Fmethod
hashCode


Finding out the object of the class

This section illustrates how to retrieve an object name that reflects the package name by using the object.getClass() method. Here is an example that provides the proper usage of the object.getClass() method in more detail.

Create a class "Fobject" with an object Checkbox. Now retrieve an object namethat reflects the package name by using the object.getClass() method.

Fobject.java:
import java.lang.reflect.*;
import java.awt.*;

public lass Fobject{
   public static void main(String[] args) {
       Checkbox bos = new Checkbox();
       printName(bos);
   }
   static void printName(Object objct) {
      Class cls = objct.getClass();
      String strng = cls.getName();
      System.out.println(strng);
  }
}

Here is the output of the Example :

C:\vignesh>javac Fobject.java

C:\vignesh>java Fobject
java.awt.Checkbox

Finding out the class fields

This section explores you, how to retrieve the fields of the class by using the getFields() method. For this we are taking an example that provides the use of the getFields() method in detailed way.

Create a class "Ffield" and create an object of this class and assign it the reference of java.util.Integer.class class.Now retrieve the class fields by using the getFields() method.

Ffield.java:
import java.lang.reflect.*;

public class Ffield {
  public static void main(String[] args) {
    Class cls = java.lang.String.class;
    Field field = cls.getFields()[0];
    String name;
    name = field.getName(); // It'll show CASE_INSENSITIVE_ORDER
    System.out.println(name);
  }
}

Here is the output of the Example :

C:\vignesh>javac Ffield.java

C:\vignesh>java Ffield
CASE_INSENSITIVE_ORDER

 Getting information about Constructor

 In this section you will learn, how to retrieve the information about the constructor by using the getConstructors() method. Here is an example that provides the usage of the getConstructors() method.

Declare a class "Fconstructor" and thencreate an object of this class and take the reference of the class java.util.Integer.class into it. Make a Constructor named constructor. Now retrieve the name of the constructor by using the getConstructors() method.

Fconstructor.java
import java.lang.reflect.*;

public class Fconstructor {
  public static void main(String[] args) {
    Class cls = java.lang.String.class;
    Constructor constructor = cls.getConstructors()[0];
    String name;
    name = constructor.getName(); // It'll show java.lang.String
    System.out.println(name);
  }
}

Here is the output of the Example :

C:\vignesh>javac Fconstructor.java

C:\vignesh>java Fconstructor
java.lang.String

No Argument Constructor Example

 In this section you will learn how to know that whether any class consists No-Argument Constructor or not ?. Here is an example that provides the usage of thenewInstance() method in more detail.
Here in our example we have used"forName()" static method of Classand then we have invokednewInstance() method to create a new object without any argument. InvokingnewInstance() method throws a NoSuchMethodException if the class does not have any no-argument constructor.

NoArgConstructor.java
import java.lang.reflect.*;
import java.util.ArrayList;

public class NoArgConstructor {
  public static void main(String str[]) {
    try {
      ArrayList list = (ArrayList) (Class.forName("java.util.ArrayList").newInstance());
      System.out.println("No-Argument Constructor exist.");
      System.out.println("New Object created Successfully");
    } catch(Exception e) {
      System.out.println("No-argument constructor does not exist.");
      System.out.println(e.getMessage());
    }
  }
}

Output:


 Getting Methods Information of a class

In this part of tutorial you will learn how to retrieve information of all methods of a class (that included in the program) byusing the getMethods() method. Here is an example that provides the usage of thegetMethods() method in more detail.

Create an object of class. Now retrieve all methods list in Method[] array. Now we can get other information of that methods by using different methods on that method object.

MethodInfo.java
import java.lang.reflect.*;
import java.util.HashSet;

public class MethodInfo {
  public static void main(String str[]) {
    HashSet set = new HashSet();
    Class classObj = set.getClass();
    Method[] methods = classObj.getMethods();
    for(int i = 0; i < methods.length; i++) {
      String methodName = methods[i].getName();
      System.out.println("Name: " + methodName);
      String returnString = methods[i].getReturnType().getName();
      System.out.println("Return Type: " + returnString);
      Class[] parameterTypes = methods[i].getParameterTypes();
      System.out.print("Parameter Types: ");
      for(int k = 0; k < parameterTypes.length; k++) {
        String parameterName = parameterTypes[k].getName();
        System.out.print(" " + parameterName);
      }
      System.out.println();
    }
  }
}

Output:



Identifying array using Reflection

 In this section we will describe you how to identify the object is Array or not ?with the use of boolean methodisArray(). Here is an example that demonstrates the use of the isArray()method for identification of Array object.
In our example we are taking two variable objects of type integer and String respectively. In these two one is an array and another is not. So when we will callisArray() method on them then Array variable "var" returns true hence you will get the following message on your command prompt. "var is an Array" and will return "false" in case of string object "notvar".

IdentifyArray.java
import java.lang.reflect.*;

public class IdentifyArray {
  public static void main(String str[]) {
    int[] var = { 1, 2, 3, 4 };
    String notvar = "Hello";
    Class varcls = var.getClass();
    Class notvarcls = notvar.getClass();
    if(varcls.isArray())
      System.out.println(" var is an Array ");
    else
      System.out.println(" var is not an Array ");
    if(notvarcls.isArray())
      System.out.println(" notvar is an Array ");
    else
      System.out.println(" notvar is not an Array ");
  }
}

Output:    



Getting Fields Information of a class

In this section of "Reflection Tutorial"you will know how to retrieve the  specific field of any class by using thegetField() method. For this we are taking an example that provides the use of thegetField() method in detailed way.

Create an object of  "Rectangle" and then by invoking getClass() method  we will have a class object that will be able to call getField() .
getField("x") returns x-axis field object
getField("y") returns y-axis  field object
getField("height") returns  height field object
getField("width") returns width  field object
Since all these fields values are of integer type so we have to use getInt() method.

Getting Field.java
import java.awt.*;
import java.lang.reflect.*;

public class GettingField {
  public static void main(String[] args) throws Exception {
    Rectangle rect = new Rectangle(50, 60);
    Field xfield = rect.getClass().getField("x");
    Field yfield = rect.getClass().getField("y");
    Field heightField = rect.getClass().getField("height");
    Field widthField = rect.getClass().getField("width");
    System.out.println("X Value = " + xfield.getInt(rect));
    System.out.println("Y Value = " + yfield.getInt(rect));
    System.out.println("Height Value = " + heightField.getInt(rect));
    System.out.println("Width Value = " + widthField.getInt(rect));
  }
}

Output:  



 Getting Component type
In this section you will come to know that how you can retrieve Component Type of an array's element. The component type of an Array is the type of array's element. For example if we have an integer type array then its component type will also beinteger.

ComponentType.java
import java.lang.reflect.*;

public class ComponentType {
  public static void main(String str[]) {
    int[] intvar = { 1, 2, 3, 4 };
    double[] doublevar = { 1.0, 2.2, 3.5, 4.8 };
    Class intcls = intvar.getClass();
    Class doublecls = doublevar.getClass();
    System.out.println(" \"intvar\" component type => " + intcls.getComponentType());
    System.out.println(" \"doublevar\" cpmponent type => " + doublecls.getComponentType());
  }
}

To run this example create and save ComponentType.java and compile it. After compilation execute ComponentType.class file.
 Output



Examine Interface Example

In this part of tutorial we will discuss how do you know that whether a given class is an "Interface" or a "Class"? 
To know that given class is an Interface or Class we can use  boolean methodisInterface() which returns true if given class is an Interface and false if it is a class.


import java.lang.reflect.*;

public class ExamineInterface {
  public static void main(String str[]) {
    Class cls = java.util.List.class;
    Class[] intfs = cls.getInterfaces();
    int len = intfs.length;
    for(int i = 0; i < len; i++) {
      System.out.println("Interface name is -->" + intfs[i].getName());
      if(intfs[i].isInterface()) {
        System.out.println(intfs[i].getName() + " is an interface.");
      } else {
        System.out.println(intfs[i].getName() + " is a class.");
      }
    }
  }
}

Output:



Class Modifier Example
In this section you will learn how to retrieve modifier's information of a class that we have taken in our program. Here is an example that provides the usage of the getModifiers() method in more detail.

Create an object of  class as you want and then call getModifiers() method through this object. We can also know is it "Public", "Abstract", "Final" withisPublic(), isAbstract(), isFinal()methods.

ClassModifier.java
import java.lang.reflect.*;

public class ClassModifier {
  public static void main(String str[]) {
    Class cls = java.util.List.class;
    int modifier = cls.getModifiers();
    if(Modifier.isPublic(modifier)) System.out.println("public");
    if(Modifier.isAbstract(modifier)) System.out.println("abstract");
    if(Modifier.isFinal(modifier)) System.out.println("final");
  }
}

Output:



Calling ( Invoking ) Methods through Reflection

In previous sections we have seen that how we can use "Reflection" to get information related to any Method. Now in this section of the tutorial you will come to know that we can also call methods of a class with the help of "Reflection".

Since methods of a class either consists of arguments or do not have any argument. So in case of no-argument method noting to worry just simply get class of that object (as we have taken "String" in our example) and after getting class , get that particular method and to invoke this method we have to use invoke() method.

CallingMethod.java
import java.lang.reflect.*;

public class CallingMethod {
  public static void main(String[] args) {
      String firstName= new String("Deepak");
      String lastName=new String("Kumar");
      String result =  new String("");
      Class cls = String.class;
      Class[] parametertype = new Class[] {String.class};
      Object[] arguments = new Object[] {lastName};
      try {
         Method concatMethod =
         cls.getMethod("concat", parametertype);
         result = (String)
         concatMethod.invoke(firstName,arguments);
         System.out.println(" Concatenated String is =>
         "+result);
         }catch (Exception e) {
         System.out.println(e);
         }
     }
}

Output:



Setting Fields Information of a class using Reflection

As in our previous example we have seen that we can get field values of a class by using the Field class. Now we can also set different field values of that class by using set() method.
In our class SettingField we have created an object of "Rectangle" and we can get fields of that object by usinggetField() method and we can retrieve values of that fields by get() method. Now we can set fields value by using set() methods. 
  
    xfield.setInt(rect,new Integer(10));
    yfield.setInt(rect,new Integer(10));
    heightField.setInt(rect,new Integer(60));
    widthField.setInt(rect,new Integer(80));

Above lines of code sets x-axis, y-axis, height, width field values. Since we are setting integer values to its field so I have used setInt() method. Here is the example code for SettingFieldclass :

SettingField.java
import java.awt.*;
import java.lang.reflect.*;

public class SettingField {
  public static void main(String[] args) throws Exception {
    Rectangle rect = new Rectangle();
    Field xfield = rect.getClass().getField("x");
    Field yfield = rect.getClass().getField("y");
    Field heightField = rect.getClass().getField("height");
    Field widthField = rect.getClass().getField("width");
    System.out.println("---->> Before Setting Values <<----");
    System.out.println("X Value = " + xfield.getInt(rect));
    System.out.println("Y Value = " + yfield.getInt(rect));
    System.out.println("Height Value = " + heightField.getInt(rect));
    System.out.println("Width Value = " + widthField.getInt(rect));
    xfield.setInt(rect, new Integer(10));
    yfield.setInt(rect, new Integer(10));
    heightField.setInt(rect, new Integer(60));
    widthField.setInt(rect, new Integer(80));
    System.out.println("---->> After Setting Values <<----");
    System.out.println("X Value = " + xfield.getInt(rect));
    System.out.println("Y Value = " + yfield.getInt(rect));
    System.out.println("Height Value = " + heightField.getInt(rect));
    System.out.println("Width Value = " + widthField.getInt(rect));
  }
}

Output:



No comments:

Post a Comment