Clarifying, you want a class (A
) that is constrained to have a particular class method (B
) and you want to pass that class as an argument to some other method (C
) and have that method (C) invoke that class method on that class (A.B()
)?
The first part, the type constraint, that can't be done. Java's type system just does not work that way.
The second part, passing a class as an argument and invoking a class method on it, that can be done using reflection. This is how to do it, correcting from your code (though you should be more careful with the exceptions than I've been in this).
private static <T extends Model> long countModel(Class<T> clazz) throws Exception
{
return (Long) clazz.getMethod("count").invoke(null);
}
The null
is the instance to invoke this on (no instance; it's a class method). The cast to Long
is required as the result of invoke()
is an Object
. The type parameter must go before the result type. And the whole thing can take any class that is a subclass of Model
as a parameter; it will just fail at runtime if the count
method isn't present. Them's the breaks.
(Also note that if you wanted to pass arguments to count()
, you'd have to specify the classes of those arguments to getMethod
and the values themselves to invoke
, in both cases as subsequent arguments. Both support Java5 variable argument lists.)