Tuesday, December 7, 2010

Break Oop's concepts - Java Reflection API

As you all know that we can not access private members of a class, but using Java Reflection API you can. Yes you can break Oops concept by accessing private variable, by calling private methods and also you can create an instance of class which is having private constructor-

Access private members of a class

/**
Class having only one private member
*/

package com.examples;
class test
{
private int youCanAccessMe;
}


Now to access "youCanAccessMe" variable -

package com.examples;
import java.lang.reflect.Field;
public class ReflectExample
{
public static void main(String args[])
{
try
{
Class cls = Class.forName("com.examples.test");
Object obj = cls.newInstance();
Field[] fields = cls.getDeclaredFields();
for( int i = 0 ; i <>fields[i].setAccessible(true);
System.out.println("Field Name-->"+fields[i].getName()+"\t"
+"Field Type-->"+ fields[i].getType().getName()+"\t"
+"Field Value-->"+ fields[i].get(obj));

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

You can get the Class object and using Class object you can also create an object of class.
Class cls = Class.forName("com.examples.test");
Object obj = cls.newInstance();
To access private member variable, you have to call setAccessible method to set accessibility level to true.
fields[i].getName() - To get name of variable
fields[i].getType().getName() - To get the type of variable
fields[i].get(obj) - To get its values
Thus Reflection is a powerful approach to analyze the class at runtime.

No comments:

Post a Comment