在Java中传递一个类("Country.class")作为参数

Amy*_*y B 0 java casting

我试图使这需要的参数的方法Country.class,User.class等等,并返回argument.count().

我将为此方法提供的所有可能的类都扩展Model并拥有该方法count().

我的代码:

private static long <T> countModel(Model<T> clazz)
{
    // there is other important stuff here, which prevents me from
    // simply by-passing the method altogether.

    return clazz.count();
}
Run Code Online (Sandbox Code Playgroud)

被称为:

renderArgs.put("countryCount", countModel(Country.class));
Run Code Online (Sandbox Code Playgroud)

然而,这根本不起作用.

我该怎么办?

And*_*anu 5

我想你想做

private long countModel(Class<? extends Model> clazz) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException
{
  Method countMethod =  clazz.getDeclaredMethod("count", null);
  return (Long) countMethod.invoke(null, null);
}
Run Code Online (Sandbox Code Playgroud)

希望这样的事情能起作用(我的反思技巧并不那么好).