Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Reflection Design Question

 
Albert Chern
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi guys,

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?

Thanks!
 
Pradeep Kadambar
Ranch Hand
Posts: 148
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Pradeep Kadambar
Ranch Hand
Posts: 148
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15485
43
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Did those people also tell you why reflection is bad? Just because someone said it is, is not a good reason...

What you are describing sounds like a perfectly reasonable case for using reflection, so I wouldn't worry about it.
 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Reflection has problems with performance

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.
 
Albert Chern
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks guys. Reflection also seemed to be the best choice to me, but I just wanted to confirm it with some experts.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic