Thursday, 12 July 2012

Reflections in Java

Reflection is a feature in the Java programming language. It allows an executing Java program to examine or "introspect" upon itself, and manipulate internal properties of the program. For example, it's possible for a Java class to obtain the names of all its members and display them.

There are three steps that must be followed to use these classes.

1. Obtain a java.lang.Class object for the class that you want to manipulate.
2. Call method defined in the java.lang.Class to get the information about the class you want to manipulate.
3. Use the reflection API to manipulate the information

Example of Reflection feature.

Reflection :


package com.lnt.scjp;

import java.lang.reflect.*;

public class Reflection {
private int f1(Object p, int x) throws NullPointerException {
if (p == null)
throw new NullPointerException();
return x;
}

public static void main(String args[]) {
try {
Class cls = Class.forName("com.lnt.scjp.Reflection");

Method methlist[] = cls.getDeclaredMethods();
for (int i = 0; i < methlist.length; i++) {
Method m = methlist[i];
System.out.println("name = " + m.getName());
System.out.println("decl class = " + m.getDeclaringClass());
Class pvec[] = m.getParameterTypes();
for (int j = 0; j < pvec.length; j++)
System.out.println("param #" + j + " " + pvec[j]);
Class evec[] = m.getExceptionTypes();
for (int j = 0; j < evec.length; j++)
System.out.println("exc #" + j + " " + evec[j]);
System.out.println("return type = " + m.getReturnType());
System.out.println("-----");
}
} catch (Throwable e) {
System.err.println(e);
}
}
}


Output:

name = main
decl class = class com.lnt.scjp.Reflection
param #0 class [Ljava.lang.String;
return type = void
-----
name = f1
decl class = class com.lnt.scjp.Reflection
param #0 class java.lang.Object
param #1 int
exc #0 class java.lang.NullPointerException
return type = int
-----

In the above class we are printing the information of the same class using the Reflection feature of the java. In the above class we have only used the Method class under the java.lang.reflect package. There are other class which the same package provide for modifications. Which can be seen in the below link.


No comments:

Post a Comment