【问题标题】:Why doesn't this generic usage work in groovy?为什么这种通用用法在 groovy 中不起作用?
【发布时间】:2015-03-05 00:05:30
【问题描述】:

学习 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() 会失败?

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

【问题讨论】:

  • 更奇怪...为什么 T.list() 有效,但 T.count() 无效?如果它在单元测试中失败,则说明 .count() 没有被很好地模拟。
  • 这在我实际运行应用程序时失败了...尚未尝试为其编写测试。

标签: grails generics groovy


【解决方案1】:

T 是一种类型。所以这并不像你期望的那样工作。你必须举行一个具体的课程(见Calling a static method using generic type)。

因此,在您的情况下,传递真正的课程也是最简单的。例如:

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"

【讨论】:

  • 这确实是我的问题。现在开始我遇到的新问题!
  • 因此作为后续行动。我已经让 create 方法以及现在使用此方法的 index 工作,但我似乎无法使用接受“实例”def show(Team instance) { respond instance } 的方法得到任何工作我尝试用 Class,T,Object ...我只是不明白我猜Groovy。当我调试时,它似乎根本没有命中该方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-16
相关资源
最近更新 更多