Learning Groovy and Grails and I am trying to simplify some controllers by making a BaseController.
I define the following:
class BaseController<T> {
public def index(Integer max) {
params.max = Math.min(max ?: 10, 100)
respond T.list(params), model:[instanceCount: T.count()]
}
}
Then I have the following:
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()]
}
*/
}
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: []
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).
So in your case it's easiest to also pass down the real class. 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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With