HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java / Java Reflection / Java Reflection – Real Usage Examples

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?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. Ken Chen

    August 17, 2019

    @Lokesh may you write a tutorial on how DI works ?

  2. Priya

    March 7, 2018

    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.

  3. javafreakers

    November 16, 2016

    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 ?

  4. sandip

    October 15, 2016

    good one..thank you.

  5. Vishal sharma

    January 27, 2015

    @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..

    • Lokesh Gupta

      January 28, 2015

      I will try to write one soon.

      • vishal sharma

        January 28, 2015

        that would be very helpful..thanks

  6. sri

    August 28, 2014

    how java used in air condition

    • Lokesh Gupta

      August 28, 2014

      🙂 You get a remote control and display panel in AC, they run on java.
      Good Read: https://www.oracle.com/java/moved-by-java/

  7. himanshu

    June 14, 2014

    sir i wanna sort this.
    how can i?
    “AFTCE123ZD”
    without using string array.

  8. Vinodkumar

    June 12, 2014

    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

    • Lokesh Gupta

      June 13, 2014

      Hey Vinod, Thanks for sharing your experience. Much appreciated.

  9. Adarsha

    June 12, 2014

    Really good article .tq u for sharing

Comments are closed on this article!

Search Tutorials

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces