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:
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
In a nutshell, generics enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods. Much like the more familiar formal parameters used in method declarations, type parameters provide a way for you to re-use the same code with different inputs.
Generics could be used to develop a better solution using a container that can have a type assigned at instantiation, otherwise referred to as a generic type, allowing the creation of an object that can be used to store objects of the assigned type.
Generic classes encapsulate operations that are not specific to a particular data type. The most common use for generic classes is with collections like linked lists, hash tables, stacks, queues, trees, and so on.
Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different data types.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With