generics in Groovy

2020-04-05 08:29发布

问题:

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

回答1:

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.



回答2:

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.