我有很多类,每个类都实现GeneralInterface
并可能附加功能接口:
interface GeneralInterface {}
class MyObjectTypeOne implements GeneralInterface { /*...*/}
class MyObjectTypeTwo implements GeneralInterface, InterOne { /*...*/}
class MyObjectTypeThr implements GeneralInterface, InterOne, InterTwo { /*...*/}
我有一个包含这些MyObjectTypeXXX
实例的列表
class ListHolder {
public static List<GeneralInterface> list = new ArrayList<>();
ListHolder() {
list.add(new MyObjectTypeOne());
list.add(new MyObjectTypeTwo());
list.add(new MyObjectTypeTwo());
// add any number of any of the types
}
}
和20-40个功能接口。这里有 2 个例子:
@FunctionalInterface
public interface InterOne {
boolean onInterOne();
static void iterate() {
for (GeneralInterface obj : ListHolder.list) {
if (obj instanceof InterOne) {
if (((InterOne) obj).onInterOne())
System.out.println("yes");
}
}
}
}
和
@FunctionalInterface
public interface InterTwo {
boolean onInterOne(String string);
static void iterate(String string) {
for (GeneralInterface obj : ListHolder.list) {
if (obj instanceof InterTwo) {
if (((InterTwo) obj).onInterTwo(string))
System.out.println("yes");
}
}
}
}
在代码的不同位置,我需要调用不同的iterate
方法:
InterTwo.iterate("S");
InterOne.iterate();
我的问题是,我需要维护iterate
所有功能接口的方法,而它们实际上都在做同样的事情:检查对象是否实现了该接口(强制转换)并使用给定的参数调用其唯一的抽象方法。
有没有一种方法,通过语法或设计,只维护一个这样做的方法?我知道通过反思有一种不好的方式来做到这一点(我展示它只是为了表明我做了我的研究,我不想要它):
static void iterate(Class<?> clazz, Object arg) {
for (GeneralInterface obj : ListHolder.list) {
if (clazz.isAssignableFrom(obj.getClass())) {
Method[] methods = clazz.getMethods();
Method functional;
for (Method m : methods) {
if (m.getModifiers() == Modifier.ABSTRACT) {
functional = m;
break;
}
}
if ((boolean) functional.invoke(obj, arg)) // cast arg or do some other trick
System.out.println("yes");
}
}
}