Possible Duplicate:
What is reflection, and why is it useful?
What is the exact use of reflection in Java? Can anyone demonstrate with an example? If there are any related concepts, please share.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Reflection is a powerful construct which is often used by underlying libraries such as Guice and Hibernate to make life easier. It is often used where a class needs to be configured and then instantiated on the fly. For example:
Here, the clazz parameter names the class to instantiate. It is assumed that the class will be a subclass of the Strategy class/interface. It is then also initiated with settings passed in through the config parameter. This allows for a highly configurable/dynamic environment.
However, reflection quite often leads to very dangerous (and malicious) code and for that reason, reflection should be avoided, unless absolutely necessary. Also keep in mind, that reflection is slower than a direct call. Here’s an actual example pulled from a production system of how NOT to use reflection.
Here, the private field in ehcache is changed and accessed. This is downright bad coding.