为什么这种通用的用法在groovy中不起作用? [英] Why doesn't this generic usage work in groovy?
问题描述
我定义了以下内容:
class BaseController< T> {
public def index(整数最大值){
params.max = Math.min(最大值:10,100)
响应T.list(参数),型号: [instanceCount:T.count()]
}
}
然后我具有以下内容:
class TeamController扩展了BaseController< Team> {
static allowedMethods = [save:POST,update:PUT,delete:DELETE]
$ b $ * / b $ b def index(整数最大值){
params.max = Math.min(max?:10,100)
响应Team.list(params),模型:[teamInstanceCount:Team.count()]
}
* /
}
每次尝试调用此函数时,都会收到一个MethodMissingException在T.count()上。为什么Team.count()可以工作,但是当我尝试使用泛型T.count()失败时?
$ b - 编辑 - (添加异常)
没有方法的签名:static java.lang.Object.count()适用于参数类型:()values:[]
所以在你的情况下,最简单的做法也是传递真实的课程。例如: Learning Groovy and Grails and I am trying to simplify some controllers by making a BaseController. I define the following: Then I have the following: Every time I try to make a call to this, I get a MethodMissingException on T.count(). Why does Team.count() work, but when I try to use generics T.count() fail? -- edit -- (Adding exception)
No signature of method: static java.lang.Object.count() is applicable for argument types: () values: [] So in your case it's easiest to also pass down the real class. E.g.:
这篇关于为什么这种通用的用法在groovy中不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! T
是一种类型。所以这不符合你的预期。您必须持有具体的类(请参阅使用泛型类型调用静态方法<一>)。
class A< T> {
私人课程< T> clazz
A(Class< T> clazz){this.clazz = clazz}
String getT(){T.getClass()。toString()}
//错误! String getX(){Tx}
String getX(){clazz.x}
}
class B {
static String getX(){returnx marks地点}
}
class C扩展了A< B> {
C(){super(B)}
}
声明新的C()。x ==x标记地点
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
is a type. So this does not work as you expect it to be. You have to hold a concrete class (see 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"