我想在作为参数给出的类上调用特定方法:
public static Entity selectEntityMenu(Class cl){ ArrayList<Entity> allEntities = cl.getAll(); //...
所有传入类(Entity的子类)都实现了静态getAll()方法。 怎么能实现呢?
答案 0 :(得分:0)
反射解决方案如下
Method getAll = cl.getDeclaredMethod("getAll");
ArrayList<Entity> allEntities = (ArrayList<Entity>) getAll.invoke(null);
现在这个解决方案非常糟糕。首先,不能保证Class
对象所代表的类具有所需的方法。其次,getAll()
方法可能返回ArrayList<Entity>
以外的其他内容,可能会在运行时导致ClassCastException
。
更好的Java 8解决方案是定义功能接口
public interface GetAll<T> {
public ArrayList<T> getThem();
}
和您的方法
public static Entity selectEntityMenu(GetAll<Entity> cl){
ArrayList<Entity> allEntities = cl.getThem();
//...
然后调用selectEntityMenu
作为
selectEntityMenu(SomeClass::getAll);
如果你只有Class
个对象可以使用,那么现在不可能这样做,但考虑重构选项。