java 参数传class,在Java中将类(“Country.class”)作为参数传递

I'm trying to make a method that takes an argument of Country.class, User.class etc, and returns argument.count().

All the possible classes that I would give to this method extend from Model and have the method count().

My code:

private static long countModel(Model clazz)

{

// there is other important stuff here, which prevents me from

// simply by-passing the method altogether.

return clazz.count();

}

Called by:

renderArgs.put("countryCount", countModel(Country.class));

However this just doesn't work at all.

How do I do this, please?

解决方案

I think you want to do

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);

}

Hopefully something like this would work (my reflection skills are not really that good).