Saturday 10 October 2015

The Reflection API and its usage

The Reflection API

Reflection is a very useful approach to deal with the Java class at runtime, it can be used to load the Java class, call its methods or analysis the class at runtime without knowing the names of the classes, and methods at compile time.

Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the JVM.

It is also possible to instantiate new objects, invoke methods and get/set field values using reflection.

Usage of Reflection in Java

Code analyzer tools
Code analyzers tools can analyze any class file passed to them using reflection.

Eclipse (Other IDEs) auto completion of method names
Eclipse provides method suggestions whenever we hit CTRL+SPACE using Reflection.
Reflection can be used to Auto code generation.

Marshaling and unmarshalling
Marshalling is the process of transforming the memory representation of an object to a data format suitable for storage or transmission.
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 reflection to injecting bean dependencies defined in configuration files. Spring 3 onwards, Annotations based dependencies can be analysed using reflection.

Parsing annotations by ORMs like Hibernate entity

ORMs like hibernate use the configuration files (not they use annotations) for defining the relationship between entities and database schemas which is processed using reflection.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...