2

I was toying with the idea of allowing module to with a class in a properties file ; something like

availableModules.properties
Contact=org.addressbook.ContactMain
Business=org.addressbook.BusinessMain
Notes=org.addressbook.Notes

...

My framework will use reflection to instantiate the relevant modules, and thereafter call methods on the relevant base classes, or pass the objects as parameters as required.

  • Is the above a good place to use reflection?
  • Are there any best practices on where to use reflection already posted on SO (I couldnt' locate one)? Could we start a list along those lines with any responses posted here?

EDIT Here's another example of the kind of scenarios I have in mind.

Some core code needed to determine the point of call. One application I saw achieved this by using reflection, another application used an exception. Would you deem the former to be a recommended scenario where reflection may be applied?

Everyone
  • 2,366
  • 2
  • 26
  • 39
  • 3
    Dupe of http://stackoverflow.com/questions/37628/what-is-reflection-and-why-is-it-useful – Graviton Sep 23 '09 at 06:21
  • Saw the question on 'What is reflection, and why is it useful?' whilst deciding whether to post (+: Please feel free to shoot me down if i'm wrong; In addition to whehter my use of reflection is right, i'm also looking for a list of scenarios where Reflection should be used; rather than why it is useful. – Everyone Sep 23 '09 at 07:25

3 Answers3

5

For a great framework supporting your idea have a look at the IOC container of the spring framework.

tangens
  • 39,095
  • 19
  • 120
  • 139
  • Yeap- this question immediately made me think of IOC – RichardOD Sep 23 '09 at 06:39
  • +1 IOC: me too. Use Spring framework, once you understood everything you won't live without it any more. – Juri Sep 23 '09 at 09:10
  • Aw c'mon guys (+: I'm looking for a list of places to use Reflection. Anyplace where IOC is mandated pretty much covers it; but UI Frameworks are just one item in the list – Everyone Sep 23 '09 at 12:46
2

Is the above a good place to use reflection?

I'd say no. If you want to do this kind of thing, you should probably be using one of the (many) existing mature frameworks that support Inversion of Control aka Dependency injection. Spring IOC is the most popular one, but there are many others. Google for "ioc framework java".

Underneath the hood, these frameworks most likely use reflection. But that doesn't mean you should reinvent the wheel.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
0

I usually used reflection if I want to dynamically use a class which information (assembly name, class name, method name, method parameters, etc) are stored in a string (text files or database).

dkartopr
  • 366
  • 2
  • 8