【问题标题】:Use groovy category in groovy shell在 groovy shell 中使用 groovy 类别
【发布时间】:2014-07-16 16:12:18
【问题描述】:

我在一些使用 Groovy 类别的 DSL 下工作,我想找到一种方法将我的 DSL 与 groovy shell 一起使用,而无需为每个命令显式编写 use(MyCategory){ myObject.doSomething() }

例如,假设我有以下玩具类别:

class MyCategory {
    static Integer plus(Integer integer, String string){
        return integer + Integer.valueOf(string)
    }
}

那么,我可以通过以下方式在groovysh中使用这个类别:

groovy> use(MyCategory){ 2 + '3' } //gives 5

那么,有没有办法为所有groovysh 命令全局设置MyCategory,这样就不必每次都将我的命令包装在use(MyCategory) { ... } 中?例如:

groovy> useGlobally(MyCategory); //call something like this only once
groovy> 2 + '3' //automatically uses MyCategory and gives 5

【问题讨论】:

    标签: groovy dsl groovyshell


    【解决方案1】:

    类别的想法是关闭元编程的范围。在这种情况下为什么不使用metaClass

    groovy:000> class MyCategory {
    groovy:001>     static Integer plus(Integer integer, String string){
    groovy:002>         return integer + Integer.valueOf(string)
    groovy:003>     }
    groovy:004> }
    ===> true
    groovy:000> Integer.metaClass.mixin MyCategory
    ===> null
    groovy:MyCategory@131fa4b> 2 + '4'
    ===> 6
    groovy:MyCategory@131fa4b> 
    

    更新:有了很多方法,您可以遍历静态方法的第一个参数,并将它们混合到相应的参数类型类中。

    class MyCategory {
        static global() {
            MyCategory.metaClass.methods
                .findAll { it.isStatic() && !it.name.startsWith("__") && it.name != "global" }
                .each { it.nativeParameterTypes[0].mixin MyCategory }
        }
    
        static Integer plus(Integer integer, String string){
            return integer + Integer.valueOf(string)
        }
    
        static String yell(String a, times) {
          a.toUpperCase() * times + "!!!"
        }
    }
    
    
    MyCategory.global()
    
    
    assert "a".yell(3) == "AAA!!!"
    assert 2+'3' == 5
    

    【讨论】:

    • 谢谢,这几乎是我想要找到的。但是如果MyCategory 包含很多对不同类的覆盖,那么我需要为每个类手动指定mixin(比如Integer)。有没有办法自动做到这一点?
    猜你喜欢
    • 1970-01-01
    • 2013-02-12
    • 1970-01-01
    • 2011-10-18
    • 1970-01-01
    • 2019-02-11
    • 2010-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多