Groovy - Can I pass a class as a parameter?

This is just a very simple example of what I want to do. There's a bit more going on in the foobar method, but that's the gist of what I'm doing. Obviously this won't work as it won't compile, but I'm wondering if I passed the class incorrectly or with the "className" parameter wrong. I know I can refactor it to take the class name string and just match it, but it seems to be a shame. It would be so beautiful and dry.

class Foo {
   String name
}

class Bar {
   String name
}

def foobar(field, className) {
   def instance = className.findByName(jsonParams.field)
   if(!instance) {
      instance = new className(name: jsonParams.field)
   }

   return instance
}

foobar(foos, Foo)
foobar(bars, Bar)

      

I don't know much Java or Groovy, so I'm not sure what is possible and not possible. Feel free to just tell me no. I tried searching the internet and didn't find anything that actually answers the question for me. Simple no would be great at this point haha.

+3


source to share


1 answer


Yes, you can pass a class as an argument - in Groovy, classes are first class citizens ( see this thread for more details ).

This construct: instance = new className(name: jsonParams.field)

actually tries to instantiate a named className

class, not the class that this variable refers to. To compile it you need to call Class.newInstance:



class Foo {
   String name
}
class Bar {
   String name
}
def foobar(String name,Class clazz) {
   def instance = clazz.findByName(name)
   if(!instance) {
      instance = clazz.newInstance(name:name)
   }

   return instance
}
foobar('foo', Foo)
foobar('bar', Bar)

      

I'm not quite sure what you want to achieve with the help of the method findByName

, although none of Foo

and Bar

is not a static method with a name findByName

, as far as I'm concerned.

+4


source







All Articles