gpt4 book ai didi

java - Groovy 中的泛型

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:19:37 26 4
gpt4 key购买 nike

下面的 Groovy 代码打印“it works”

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

printIt(String.class)

即使参数不满足约束 Class<? extends Exception>

我的理解是,这是因为:

  1. Java 泛型中的类型删除意味着没有运行时泛型类型检查
  2. Groovy 中没有编译时类型检查

这两点意味着 Groovy 中实际上没有检查有界泛型类型。有什么方法可以检查(在运行时)Class对象传递给 printIt满足约束 ? extends Exception

谢谢,唐

最佳答案

看看这个 link .

[...]In some ways this is at odds with theemphasis of dynamic languages where ingeneral, the type of objects can notbe determined until runtime. ButGroovy aims to accomodate Java'sstatic typing when possible, henceGroovy 1.5 now also understandsGenerics. Having said that, Groovy'sgenerics support doesn't aim to be acomplete clone of Java's generics.Instead, Groovy aims to allow genericsat the source code level (to aid cutand pasting from Java) and also whereit makes sense to allow goodintegration between Groovy and Javatools and APIs that use generics.[...]

总之,我认为不可能在运行时获取该信息。

关于java - Groovy 中的泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2008291/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com