如何调用作为参数传递的子类的方法?

时间:2014-04-16 16:47:19

标签: java class

我想在作为参数给出的类上调用特定方法:

public static Entity selectEntityMenu(Class cl){
    ArrayList<Entity> allEntities = cl.getAll();
//...

所有传入类(Entity的子类)都实现了静态getAll()方法。 怎么能实现呢?

1 个答案:

答案 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个对象可以使用,那么现在不可能这样做,但考虑重构选项。

相关问题