Groovy中的泛型 [英] generics in Groovy

查看:286
本文介绍了Groovy中的泛型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的Groovy代码打印它有效

  def printIt(Class< ;? extends Exception> clazz){
printlnit works
}

printIt(String.class)

即使参数不满足约束 Class <?>扩展异常>



我的理解是,这是因为:


  1. 在Java泛型中键入erasure意味着没有运行时泛型类型检查

  2. Groovy中没有编译时类型检查

  3. 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:

    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

    解决方案

    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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆