簡體   English   中英

在groovy shell中使用groovy類

[英]Use groovy category in groovy shell

我正在使用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

該類別的想法是縮小元編程的范圍。 為什么不在這種情況下使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM