Everyone
Everyone

Reputation: 2376

Best Practices: What to use Reflection for?

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.

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?

Upvotes: 2

Views: 1787

Answers (3)

dkartopr
dkartopr

Reputation: 366

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).

Upvotes: 0

Stephen C
Stephen C

Reputation: 719299

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.

Upvotes: 2

tangens
tangens

Reputation: 39743

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

Upvotes: 5

Related Questions