Groovy中的泛型 [英] generics in Groovy
问题描述
下面的Groovy代码打印它有效
def printIt(Class< ;? extends Exception> clazz){
printlnit works
}
printIt(String.class)
即使参数不满足约束 Class <?>扩展异常>
我的理解是,这是因为:
- 在Java泛型中键入erasure意味着没有运行时泛型类型检查
- Groovy中没有编译时类型检查
- Type erasure in Java generics means there's no run-time generic type checking
- There is no compile-time type checking in Groovy
ol>
这两点意味着在Groovy中实际上不会检查有界泛型类型。有什么方法可以检查(在运行时)传递给 printIt
的 Class
对象满足约束?扩展异常
谢谢,
Don
查看此链接。
[...]在某些方面,这与动态语言的
重点不一致,其中
一般而言,对象的类型不能
要确定直到运行时间。但是,
Groovy旨在尽可能地适应Java的
静态类型,因此
Groovy 1.5现在也可以理解
泛型。话虽如此,Groovy的
泛型支持并不打算成为Java泛型的
完整克隆。
相反,Groovy的目标是在源代码级别允许泛型
(以帮助减少
并从Java中粘贴)以及
允许良好
Groovy和Java之间的集成
使用泛型的工具和API [...]
总之,我认为可以在运行时获得这些信息。
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
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.
这篇关于Groovy中的泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!