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.
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.
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 !!
All of my websites are hosted on Bluehost. Why? Because they make it incredibly easy to get a new site up and running with their one-click automatic WordPress Blog installation.
You can use your Bluehost account to host multiple domains—no need to pay more for hosting when you’re ready to start another website.