Tuesday 19 June 2012

Fundas using Reflection

Reflection is one of the most powerful features in Java Programming language. You must be familiar with Object Oriented programming where you create blueprints called classes and make objects out of them, call instance methods using those objects or call static methods using the class.

Using Reflection, you can create objects from outside the class's namespace. In simple terms, you can create objects at runtime. Hypothetically, if at compile time there was a code to find out the number of objects for the class and if reflection's used, this code would fail. Reflection is so powerful that you would be able to hack into the class's methods and attributes. Below is a sample snippet which demonstrates Reflection

try
{
Class c = Class.forName("classname");     // Class handler
Field f = c.getField("fieldname");        // Get the field
Method m[] = c.getDeclaredMethods();    // Get all methods
}catch(Exception ex)
{
ex.printStackTrace();
}

The above was just a sample of Reflection's capabilities. For design a comprehensive Debugging tool, the best approach to go for is Reflection. This is because as an ideal case, a debugger must see the code from outside it's domain.

Reflection is also used to get all implemented Interfaces, finding out the superclass of a given class, getting information about constructors and much more.

1 comment:

Do you like our Content?