What is reflection, and why is it useful?
I\'m particularly interested in Java, but I assume the principles are the same in any language.
Reflection is an API which is used to examine or modify the behaviour of methods, classes, interfaces at runtime.
java.lang.reflect package
.The java.lang
and java.lang.reflect
packages provide classes for java reflection.
Reflection can be used to get information about –
Class The getClass()
method is used to get the name of the class to which an object belongs.
Constructors The getConstructors()
method is used to get the public constructors of the class to which an object belongs.
Methods The getMethods()
method is used to get the public methods of the class to which an objects belongs.
The Reflection API is mainly used in:
IDE (Integrated Development Environment) e.g. Eclipse, MyEclipse, NetBeans etc.
Debugger and Test Tools etc.
Advantages of Using Reflection:
Extensibility Features: An application may make use of external, user-defined classes by creating instances of extensibility objects using their fully-qualified names.
Debugging and testing tools: Debuggers use the property of reflection to examine private members on classes.
Drawbacks:
Performance Overhead: Reflective operations have slower performance than their non-reflective counterparts, and should be avoided in sections of code which are called frequently in performance-sensitive applications.
Exposure of Internals: Reflective code breaks abstractions and therefore may change behaviour with upgrades of the platform.
Ref: Java Reflection javarevisited.blogspot.in