What is Reflection?
A group of methods, starting in the classes java.lang.Class and java.lang.ClassLoader used to dynamically find Java Classes and execute code on them. It provides mechanisms for finding the classes, instantiating instances of the class, locating and executing methods, and accessing data members.
Why would you use Reflection?
There are a host of reasons. Some examples:
- Dynamic 'Drop Ins': You want to be able to expand your application by simply dropping in JARs or Classes into the class path after the application has been deployed. This means the 'main' part of the application doesn't know anything about what classes are available at run time, and so can't reference them directly. Reflection can be used to locate and load these drop-ins, then automatically execute code on the drop in which would 'register' it with the main application - making it available for use. This is common in a lot of open source image manipulation applications where users can write drop ins for custom analysis, or for importing various image formats. It can be used in games to provide user-generated levels, etc...
- Mapping 'events' to 'actions'. This is very common in situations where an application has very distinct actions to perform based on some dynamic event. The event occurs and an action is supposed to happen. But there can be lots of events and they can change over time. You define each event and each action as its own class, and then provide some mapping between them. But because the events can change you don't want to have to modify the application each time the event occurs. So you create the classes for events and actions, then create a configuration file to define what events can occur and how to map those events to their corresponding actions. Your main app would read the configuration file and use Reflection to generate the instances of the Events and Actions, and to map them appropriately. Now when you add new events, retire old ones, change what actions need to occur, etc... you no longer have to re-compile your entire application. You just put the new .class files in and change a config file. For examples, look at
Servlet Engines like
Tomcat, or any
JEE server.
- It is sometimes nice to have a simple to use script type interface to present to the world, when your users aren't programmers. This might include auto-completion or hints, drop-down lists to suggest values, variables, or methods... On the back end you want normal Java objects to make it easy to interact with the rest of your application. Reflection can be used to find all the available classes, methods and members of those classes so you can present them to the user. This is how JavaBeans and the Introspector works, and is used by some GUI building tools and some JEE tools like the
JSP EL markup.