为什么这种通用用法在groovy中不起作用?

时间:2015-03-05 00:05:30

标签: grails generics groovy

学习Groovy和Grails,我试图通过制作BaseController来简化一些控制器。

我定义了以下内容:

class BaseController<T> {

    public def index(Integer max) {
        params.max = Math.min(max ?: 10, 100)
        respond T.list(params), model:[instanceCount: T.count()]
    }
}

然后我有以下内容:

class TeamController extends BaseController<Team> {
    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    /*
    def index(Integer max) {
        params.max = Math.min(max ?: 10, 100)
        respond Team.list(params), model:[teamInstanceCount: Team.count()]
    }
    */
}

每当我尝试调用它时,我在T.count()上得到一个MethodMissingException。为什么Team.count()工作,但是当我尝试使用泛型T.count()失败?

- 编辑 - (添加例外) 没有方法签名:static java.lang.Object.count()适用于参数类型:()values:[]

1 个答案:

答案 0 :(得分:2)

T是一种类型。所以这不会像你期望的那样有效。你必须持有一个具体的课程(见Calling a static method using generic type)。

所以在你的情况下,最简单的方法是传递真正的课程。 E.g:

class A<T> {
    private Class<T> clazz
    A(Class<T> clazz) { this.clazz = clazz }
    String getT() { T.getClass().toString() }
    // wrong! String getX() { T.x }
    String getX() { clazz.x }
}

class B {
    static String getX() { return "x marks the place" }
}

class C extends A<B> {
    C() { super(B) }
}

assert new C().x=="x marks the place"
相关问题