Java Reflection – Real Usage Examples

Reflection is one of those things like multi-threading where everyone with experience of it says “Don’t use it unless you absolutely have to”.

Above quote is absolutely true for all for us alike. In my previous tutorial, I discussed basics of annotation in which I discussed the usage of reflection to read the applied annotations on a class or a method. This immediately back-fired me with lots of requests to come up with some real life “good” examples of reflection, and possible scenarios where a developer will be needing it. I promised to come up with my leanings/thoughts on this specific topic, and so here in this post, I will discuss the same i.e. real life practical examples of reflection in java.

Example uses of reflection for impatients

Code analyzer tools
Eclipse auto completion of method names
Marshalling and unmarshalling
Spring Framework for creating the beans
Parsing annotations by ORMs like hibernate entity
Junit Testcases

When somebody would need Reflection?

More than a few professional programmers would answer “as rarely as possible, maybe even never.”

Having said that in one sentence, let me elaborate it further. Java is strongly typed language with all the “good” features of OOPs. In practical, if you know the classes you are dealing with in your application, you may never ever come across a situation where you will need reflection. “Never ever”. You can accomplish any task, fulfill any requirement without reflection when you know the classes you are going to use.

But as soon as, you are told to deal with classes which you don’t know at time of writing the code, and you must write code in too general way such that it can handle any class type then you will need reflection to do the job.

For example, you are told to write a code analyzer which is able to look inside any class; and list down it’s all private method then you can do this only by reflection. Generally, It is said that whenever you don’t know, at compile time, the type that should be instantiated or the method that should invoked, you will need reflection.

Few real examples of Reflection

Having talked about need of reflection in real life application programming, it’s time to list down some instances where reflection is used to accomplish certain objectives.

Code analyzer tools

Code analyzers tools do lots of different things with your code. They do static analysis of syntax, show optimization tips and even report error conditions, and many more such things. They are written in a way such that they can analyze any class file passed to them to analyze. How can they do it without looking inside the class. Clearly, they use reflection to this analysis.

Eclipse (Other IDEs) auto completion of method names

Ever stressed your mind, how eclipse is able to provide you method suggestions whenever you hit CTRL+SPACE, even when you are not finished with writing that class. Reflection does this magic.

I have worked in a team which developed an eclipse plugin for generating REST API sourcecode, for methods defined in some interfaces. It used to create one REST API per interface method, and using wizard you can specify the other REST specific things such as HTTP method (GET, PUT, POST, DELETE), query parameters, path parameters and return values. Return value was a JAXB annotated class which was also generated by plugin. And almost 90% of the logic for code generation was written around reflection only.

In fact, reflection is heavily used in plugins for these kind of IDEs; be it eclipse, or IntelliJ or any other IDE for that matter.

Marshalling and unmarshalling

JAXB/Jattison and other marshalling/unmarshaling libraries heavily use reflection for XML (or JSON) to/from java beans code. They look up all annotated attributes in java bean, analyze their overall attributes and generate XML tags for them. The same is valid for unmarshaling as well.

Spring Framework for creating the beans

Spring framework uses dependency injection (DI) to populate the dependencies into beans defined in config files. DI framework actually heavily uses reflection for injecting these bean dependencies.

Spring 3 onwards, you can define the dependencies using annotations as well, using autowiring. Annotations are analyzed for dependencies injection using reflection only.

Parsing annotations by ORMs like hibernate entity

ORMs like hibernate use the config files (not they use annotations) for defining the relationship between entities and relationship between entity and database schemas. All this information is processed using java reflection capability.

Junit Testcases

If you remember the previous versions of Junit, then to run a testcase all you cad to do, was name a method starting with test e.g. testMethod1(), testCode2() etc. Junit processor was using reflection to iterate over all methods in class, and find-out methods starting with test and run this as testcase.

In later version, the naming convention to start with test was replaced with usage of annotations, but the usage of reflection is much more similar.

Summary

Somewhere I have read this quote:

“When you will need reflection; you will know it”.

So, my advice to all my dear friends is, just learn the basics and don’t put too much efforts on learning the advance concepts. You can learn them whenever you will need them, and it’s very rare that you will get many chances to apply your knowledge.

That’s all for this topic. I will be glad to hear your thoughts.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

13 thoughts on “Java Reflection – Real Usage Examples”

  1. Java’s considered one of the most pervasive and common coding languages used today. Whether building applications for consumers or servers, the scalable programming language seems to pop up everywhere.

    Reply
  2. Hi Lokesh,

    This is very nice article. I have one questions. You have mentioned that eclipse uses Reflection for auto -assist option. But reflection work on run time and auto -assist is before run time. Could you please explain how it work ?

    Reply
  3. @Lokesh.. thanks for providing d importance of reflection and practical usage.
    I want to learn reflection… n I believe that you explain the topics in a simple way…
    so i want to ask.. Is there any tutorial on reflection that u suggest..
    tutorial in ur way wud be better…
    thanks in advance…
    n thanks for sharing ur knowledge..

    Reply
  4. Hi Lokesh,

    Regarding the Reflection, We used most the project the reflection for the following use cases,

    1. When we wanted to Convert the Data Base Model to DTO object which is used for transfer also used for displaying the front end page – In one word Populating the data.

    2. When we wanted convert the Data back to Model when we wanted to save the data in Data base- In one word Reverse Populator
    import org.apache.commons.beanutils.BeanUtils;

    /**
    * This populator is for populate all simples fields in productData like (String, integer, boolean and so on).
    */
    public class EplusFullProductPopulator extends ProductPopulator
    {
    @Override
    public void populate(final ProductModel source, final ProductData target) throws ConversionException
    {
    for (final Field field : target.getClass().getDeclaredFields())
    {
    try
    {
    BeanUtils.setProperty(target, field.getName(), getProductAttribute(source, field.getName()));
    }
    catch (final IllegalAccessException e)
    {
    //Just ignore the field and keep looking all fields
    }
    catch (final IllegalArgumentException e)
    {
    //Just ignore the field and keep looking all fields
    }
    catch (final InvocationTargetException e)
    {
    //Just ignore the field and keep looking all fields
    }
    }
    }
    }

    Or we can take Advantage of Opebn source Framework which uses same above logic and gives more flexibility when we need data type conversation too i,.e Int to float or String to Integer or Formatted String whatever.
    So to take advantage of such we used a Dozzer Mapper: http://dozer.sourceforge.net/documentation/about.html

    Thanks
    Vinod

    Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.