Sta*_*sky 5 dsl groovy groovyshell
我正在使用 Groovy 类别在一些 DSL 下工作,我想找到一种方法来将我的 DSL 与 groovy shell 一起使用,而无需use(MyCategory){ myObject.doSomething() }为每个命令显式编写。
例如,假设我有以下玩具类别:
class MyCategory {
static Integer plus(Integer integer, String string){
return integer + Integer.valueOf(string)
}
}
Run Code Online (Sandbox Code Playgroud)
然后,我可以通过groovysh以下方式使用此类别:
groovy> use(MyCategory){ 2 + '3' } //gives 5
Run Code Online (Sandbox Code Playgroud)
那么,有没有办法MyCategory为所有groovysh命令全局设置,这样就没有必要每次都将我的命令包装在use(MyCategory) { ... }?例如:
groovy> useGlobally(MyCategory); //call something like this only once
groovy> 2 + '3' //automatically uses MyCategory and gives 5
Run Code Online (Sandbox Code Playgroud)
类别的想法是关闭元编程的范围。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>
Run Code Online (Sandbox Code Playgroud)
更新:对于很多方法,您可以迭代静态方法的第一个参数并将它们混合到相应的参数类型类中。
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
216 次 |
| 最近记录: |