在Java中将类(“Country.class”)作为参数传递 [英] Passing a class ("Country.class") as an argument in Java
本文介绍了在Java中将类(“Country.class”)作为参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图创建一个接受 Country.class
, User.class
等参数的方法,并返回 argument.count()
。
I'm trying to make a method that takes an argument of Country.class
, User.class
etc, and returns 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();
}
Called by:
$ b
Called by:
renderArgs.put("countryCount", countModel(Country.class));
但是这根本不起作用。
我该如何做?
推荐答案
我想你想做
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).
这篇关于在Java中将类(“Country.class”)作为参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文