在groovy shell中使用groovy类 [英] Use groovy category in groovy shell

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

问题描述

我在使用Groovy类别的一些DSL下工作,我想找到一种方法来使用我的DSL与groovy shell而不明确写入 use(MyCategory){myObject.doSomething()} 为每个命令。

I am working under some DSL using Groovy categories and I would like to find a way to use my DSL with groovy shell without explicitly writing use(MyCategory){ myObject.doSomething() } for each command.

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

For example, suppose I have the following toy category:

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

>

Then, I can use this category in groovysh in the following way:

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

那么,有没有办法为全部 groovysh 命令全局设置 MyCategory ,因此每次将我的命令封装在 use(MyCategory){...} ?例如:

So, is there any way to set up MyCategory globally for all groovysh commands, so it will not be necessary to each time wrap my commands in use(MyCategory) { ... }? For example:

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> 






更新:With很多方法,你可以遍历静态方法的第一个参数,并将它们混入各自的参数类型类中。


Update: With a lot of methods, you can iterate through the first parameters of the static methods and mixin them into the respective parameter type class.

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

这篇关于在groovy shell中使用groovy类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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