Tuesday 24 June 2014

Java Reflections on inner classes

Java Reflections is another powerful feature of Java that enables you to inspect the contents of java classes in run time without even knowing the name of the class.

Consider this scenario that you have an access to java object and you want to read the following properties of the object:

1. Object's class name
2. Details of the fields in the class
3. Details of the methods present in classes and etc.

Java reflections allows you to perform the above mentioned activities with its powerful feature and you can find more details about it here.

Consider another scenario, that you have an access to the object that is an instance of inner class of another class. Now you want to perform the same activities that are listed above on the inner class.

In this blog, I am going to explain how to inspect the fields and properties of inner classes using Java reflections.

Say, you are having access to the object (innerObj), which is an instance of the inner class 'innerClass' (say, its enclosing class is com.test.outerClass').

Whenever you fetch the name of the object innerObj with below statement

                   innerObj.getClass().getName();

it will return the string value as 'com.test.outerClass$innerClass'

With this value as a reference - we can obtain the name of the outer class, as below:

                String parent = innerObj.getClass().getName().split("\\$")[0];

From then on, we can get the access to inner class details as below:

Class<?> enclosingClass = Class.forName(parent);
Object enclosingInstance = enclosingClass.newInstance();

Class<?> innerClass = Class.forName(myObj.getClass().getName());
Constructor<?> ctor = innerClass.getDeclaredConstructor(enclosingClass);
Object innerInstance = ctor.newInstance(enclosingInstance);

Field[] fields = innerClass.getDeclaredFields();

Now, we can perform various operations as detailed in the Java reflections on 'innerClass' and inspect the various attributes of inner classes.

No comments:

Post a Comment