Hi,
I have read about Java Reflections but till date it has been a vague concept to me. Can someone give a brief details with short example on how to use reflections in Java ?
Thanks.
Hi,
I have read about Java Reflections but till date it has been a vague concept to me. Can someone give a brief details with short example on how to use reflections in Java ?
Thanks.
It's primarily to be used to access classes/methods/fields programmatically (i.e. during runtime instead of compiletime). Good real world API's which uses reflection intensively are ORM's like Hibernate/JPA.
You can find here a Sun tutorial on the subject (click Next link at the bottom to paginate through it).
I guess the article 'Using Java Reflection' found on sun.com might be a good starting point.
I have read about Java Reflections but till date it has been a vague concept to me.
Here is a quick into to reflection in java:
Structural introspection. Basic reflection deals with the introspection of object at run-time. This means that you can learn the structure of objects and classes at run-time programmatically, e.g. get the class of the object, list the methods of the class, list the fields defined in the class, etc.
Reflective invocation and instantiation. With reflection you can invoke a method at run-time which is not defined at compile-time, e.g. invoke method named M on object O, where M is read in a configuration file. You can also instantiate object dynamically without knowing the class at compile-time.
Annotations. Then you can move one level up in the meta levels, and play with annotations. Annotations describe other elements such as class, method and fields. Many framework rely on this.
Dynamic proxy. Dynamic proxy can be generated at run-time. In this case, it's really like if you create a class dynamically at run-time. To use with care, but definitively handy and powerful in some cases.
I guess you will start with structural introspection. There are links to tutorials in the other answers, but I hope this gives you an overview of what else can be done.