我正在使用Groovy类别在一些DSL下工作,我希望找到一种方法,在groovy中使用我的DSL,而无需为每个命令显式地编写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那么,是否有任何方法可以为所有MyCategory命令全局设置groovysh,所以不必每次在use(MyCategory) { ... }中包装我的命令?例如:
groovy> useGlobally(MyCategory); //call something like this only once
groovy> 2 + '3' //automatically uses MyCategory and gives 5发布于 2014-05-27 16:49:09
这个类别的思想是关闭元编程的范围。为什么不在这种情况下使用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> Update:使用许多方法,您可以迭代静态方法的第一个参数,并将它们混合到相应的参数类型类中。
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' == 5https://stackoverflow.com/questions/23894653
复制相似问题