This week's book giveaway is in the Mac OS forum. We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line! See this thread for details.
Hi. As you can see i am trying to understand how reflection works.
Can someone help with me out with the process "reflection" or any "Java application startup" goes through?
Have been reading the docs at webpage to understand the jvm process. The docs out there explain reflection and not the jvm process of "class loading" which i think plays a crucial role before reflection kicks in.
Any help to find appropriate docs or explanation of how a jvm starts up an application would be appreciated.
I'm not sure exactly what you want to know - are you not clear about what the concept of reflection is, or are you just asking what it is useful for?
Normally, when you write a Java program, and you use classes that are for example in libraries (including the standard Java API), the compiler has to know about those classes - you have to have the class files for all those classes somewhere (in a directory or JAR file) and they have to be on the classpath or somewhere else so that the compiler can find them.
Suppose that you are writing a system that can be extended via plug-ins. There are many real systems which have this ability - for example, IDEs such as Eclipse and NetBeans have a plug-in architecture.
Your system needs to be able to load plug-ins and call methods in the classes of a plug-in. But note that those plug-ins are not available when you are writing your system, so you can't write your code so that you can directly call methods in plug-ins. In fact, it's most likely that the plug-ins won't even exist yet when you are writing your system, and you don't even know the class names of the classes in the plug-ins.
What you could then do is define an interface for plug-ins, for example something like this:
And then require that people who write plug-ins implement that interface.
In your system, you would use reflection to load a plug-in dynamically. You could get the name of the class that implements the PlugIn interface from a configuration file. You can then load that class with Class.forName(className); and use reflection to call the methods.
Yes, though this would tie whatever you are writing very much into the implementation of whatever you are reflecting over. Not a very safe thing to do. For example, if you call a private method via reflection that relies on state initialized in the method that accesses it you'll get unexpected behaviour.