Monday, January 26, 2009

Using Reflection to get around hard-coded dependencies

Spring famously has no cycles in it's dependency graph:
Obviously writing applications is different to writing frameworks, and we can't always take the time to get things so polished. Also by the nature of the beast the domain model will (should!) pervade the entire application (domain model should be the root of your graph, with services/repositories/ etc depending on them).

Sometimes though you may want to enable some functionality if an object is an instance of some special class, without introducing explicit dependencies on those classes. reflection is your friend!!
Of course the price is that you loose type-safety, so be warned here be dragons!!

simply at runtime see if the string representing the class name is the class you want to twiddle, if it is, reflectively invoke your methods enabling additional functionality, otherwise continue on in the boring type-safe way that only deals with the interface or bace class you're dealing with. The key here is that by default you deal with a standard interface or base class (such as javax.activation.DataSource), and only if the instance of the object has the extra bits you want (eg, then you selectively elect to do extra. Spring does this quite a lot with it's own DataSource wrappers internally.

handy sometimes...

No comments: