views:

43

answers:

1

I'm trying to take advantage of the fact that groovy is more dynamic than java. I'd like to have a block of code that does

TypeA type = //do something to build an object
TypeA dbType = TypeA.findBySomethingAndSomething(something, somethingelse)
if(dbType != null)
   type.id = dbType.id
type.save()

but that can work for multiple objects that support the same findBySomethingAndSomething method.

Is it possible to say

def type = //do something to build an object
def dbType = type.findBySomethingAndSomething(type.identifier, type.otheridentifier)
if(dbType != null)
   type.id = dbType.id
type.save()

Is there a "better" way to accomplish this? I'm trying to avoid a large switch statement or if / else series that does essentially the same thing for each type.

+2  A: 

You can always get the class object from an instance via instance.getClass(). Therefore the following should work:

instance.getClass().findBySomethingAndSomething(type.identifier, type.otheridentifier)

as long as the instance's class supports findBySomethingAndSomething

Don
Consider using getClass() instead. Won't make much difference in this case - but it's a good habit to get into in case 'instance' is ever a Map.
John Stoneham
Good advice John, this has caught me out a few times when tests pass a map to mock an instance - I've updated my response.
Don