This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
I have a program that can run with different sources of input as long as I give it a class that implements my Input interface. For example, I might have classes called TextInput or DatabaseInput that feed my program data.
I need to specify which input type to use on the command line, and what I do now is pass the class name as an argument and use reflection to construct an instance. People have told me that reflection is bad, however. Is there a better way to accomplish what I need?
You will need reflection to create desired objects at runtime. In my project I have a similar situation were I create service objects configured in XML.
Joined: Oct 18, 2004
You will need reflection to create desired objects at runtime. In my project I have a similar situation were I create service objects configured in XML. Reflection has problems with performance. So the cache the object and use the interface methods to avoid any lookup.
This is a bit of an urban myth these days. JVMs handle reflection well now.
People have told me that reflection is bad
The main reason I hesitate to use it is because it removes compile time checking. So you shift the point where you discover a programming error from the compiler to run time, and as a result (without a good, comprehensive set of unit tests) things get missed. It also makes refactoring difficult.
That aside though, your example sounds like a good candidate for reflection.