提问者:小点点

有没有办法在Groovy中参数化混合?


我可以以某种方式混合一个带有参数化构造函数的类吗?

像这样的东西:

class RenderedWithTemplates {
   def templates = []

   RenderedWithTemplates(templates) { ... }

   ...

}

@Mixin(RenderedWithTemplates(show: "showAddress.gsp", add: "addAddress.gsp")
class Address { ... }

共1个答案

匿名用户

我找到了2007年[0]的mixin提案,但GroovyDefault方法#mixin[1]方法不支持参数化混合,也不支持@Misin。

从上面的代码示例中我可以看出,您需要找到一种方法来混合GSP与您的(域)类相关联的视图信息。对于这种情况,另一种(并且稍微有点格式化的;)方法是将RenderedWellTemplate实现为注释,其中包含一个包含GSP视图信息的闭包参数:

import java.lang.annotation.*

@Retention(RetentionPolicy.RUNTIME)
@interface RenderedWithTemplates {
    Class value()
}

@RenderedWithTemplates({ [show: "showAddress.gsp", add: "addAddress.gsp"] }) 
class Address {}

// shows how to read the map with all the GSP infos

def templateInfo = Address.getAnnotation(RenderedWithTemplates)
def gspMap = templateInfo.value().newInstance(this, this).call()

[0] http://docs.codehaus.org/display/GroovyJSR/Mixins

[1] http://groovy.codehaus.org/api/org/codehaus/groovy/runtime/DefaultGroovyMethods.html