Saturday, April 5, 2014

Object reflection in Java

Problem

Explain what object reflection is in Java and why it is useful.

Solution

The name reflection is used to describe code which is able to inspect other code in the same system (or itself).
For example, say you have an object of an unknown type in Java, and you would like to call a 'doSomething' method on it if one exists. Java's static typing system isn't really designed to support this unless the object conforms to a known interface, but using reflection, your code can look at the object and find out if it has a method called 'doSomething' and then call it if you want to.
So, to give you a code example of this in Java (imagine the object in question is foo) :
Method method = foo.getClass().getMethod("doSomething", null);
method.invoke(foo, null);

So, following are the examples of the reflective information which we can get:
  1. Getting information about methods and fields present inside the class at run time.
  2. Creating a new instance of a class.
  3. Getting and setting the object fields directly by getting field reference, regardless of what the access modifier is.

public static void main(String[] args) {
    try {
        Class c = Class.forName("java.sql.Connection");
        Method m[] = c.getDeclaredMethods();
        for (int i = 0; i < 3; i++) {
            System.out.println(m[i].toString());
        }
    } catch (Throwable e) {
        System.err.println(e);
    }
}

This code's output is the names of the first 3 methods inside the "java.sql.Connection" class (with fully qualified parameters):
public abstract void java.sql.Connection.setReadOnly(boolean) throws java.sql.SQLException
public abstract void java.sql.Connection.close() throws java.sql.SQLException
public abstract boolean java.sql.Connection.isReadOnly() throws java.sql.SQLException

Why it is useful:
  • Helps in observing or manipulating the runtime behavior of applications. 
  •  Useful while debugging and testing applications, as it allows direct access to methods, constructors, fields, etc.
One very common use case in Java is the usage with annotations. JUnit 4, for example, will use reflection to look through your classes for methods tagged with the @Test annotation, and will then call them when running the unit test.
There are some good reflection examples to get you started at http://docs.oracle.com/javase/tutorial/reflect/index.html
And finally, yes, the concepts are pretty much similar in other statically types languages which support reflection (like C#). In dynamically typed languages, the use case described above is less necessary (since the compiler will allow any method to be called on any object, failing at runtime if it does not exist), but the second case of looking for methods which are marked or work in a certain way is still common.

Reference
http://tianrunhe.wordpress.com/2012/04/15/object-reflection-in-java/
http://stackoverflow.com/questions/37628/what-is-reflection-and-why-is-it-useful 

0 comments:

Post a Comment