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

Java 如何对作为参数传递的子类调用方法?,java,class,Java,Class,我想对作为参数给定的类调用一个特定方法,如下所示: 公共静态实体selectEntityMenu(类别cl){ ArrayList allenties=cl.getAll(); //... 所有传入的类(实体的子类)都实现静态getAll()方法。 如何实现这一点?反射解决方案如下 Method getAll = cl.getDeclaredMethod("getAll"); ArrayList<Entity> allEntities = (ArrayList<Entity&

我想对作为参数给定的类调用一个特定方法,如下所示:

公共静态实体selectEntityMenu(类别cl){
ArrayList allenties=cl.getAll();
//...
所有传入的类(实体的子类)都实现静态getAll()方法。
如何实现这一点?

反射解决方案如下

Method getAll = cl.getDeclaredMethod("getAll");
ArrayList<Entity> allEntities = (ArrayList<Entity>) getAll.invoke(null);
你的方法是什么

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

如果你只使用<代码>类< /代码>对象,那么这不一定是可能的,但是考虑重构选项。

使用反射。查看<代码>方法< /代码>类。或者更好的是,重构并使用命令模式。将参数类型更改为<代码>类。也许我做了一些错误但这不起作用。非常感谢。r您的回答!那么函数接口是否只适用于非类对象?我试图让它适用于类,但无法。@0ax1 Th
SomeClass::getAll
是一个方法引用。您也可以使用lambda表达式。这些都已解释。或者,您可以创建
getAll
的子类并传递insta好吧,我会仔细看看这些东西。谢谢你的时间。
public interface GetAll<T> {
    public ArrayList<T> getThem();
}
public static Entity selectEntityMenu(GetAll<Entity> cl){
    ArrayList<Entity> allEntities = cl.getThem();
//...
selectEntityMenu(SomeClass::getAll);