views:

92

answers:

2
+3  Q: 

generics in Groovy

Hi,

The following Groovy code prints "it works"

def printIt(Class<? extends Exception> clazz) {
  println "it works"
}

printIt(String.class)

even though the parameter doesn't satisfy the constraint Class<? extends Exception>

My understanding is that this is because:

  1. Type erasure in Java generics means there's no run-time generic type checking
  2. There is no compile-time type checking in Groovy

These two points means there's effectively no checking of bounded generic types in Groovy. Is there any way I can check (at runtime) that the Class object passed to printIt satisfies the constraint ? extends Exception

Thanks, Don

+3  A: 

Check out this link.

[...]In some ways this is at odds with the emphasis of dynamic languages where in general, the type of objects can not be determined until runtime. But Groovy aims to accomodate Java's static typing when possible, hence Groovy 1.5 now also understands Generics. Having said that, Groovy's generics support doesn't aim to be a complete clone of Java's generics. Instead, Groovy aims to allow generics at the source code level (to aid cut and pasting from Java) and also where it makes sense to allow good integration between Groovy and Java tools and APIs that use generics.[...]

In conclusion, I don't think it's possible to obtain that information at runtime.

bruno conde
I wonder what exactly is meant by: 'Groovy currently does a little further and throws away generics information "at the source level"'
Don
I think this means that generic information is simply ignored in groovy. In Java, generics information is removed but the appropriate casts and static type checking is made.
bruno conde
A: 

Since you know it's supposed to be an Exception, this works in Java (or Groovy):

// true if the class is a subclass of Exception
Exception.class.isAssignableFrom(clazz);

That in no way uses the generic information, but that wouldn't be available in Java either.

noah