mxalbert1996
2019-05-12 00:25:56 +08:00
没必要用反射啊,假设你有 A 和 B 两个类都实现了 Interface 这个接口,那你可以这么写:
public class Test {
private Class[] classes = {A.class, B.class};
private HashMap<Class, Set<Interface>> sets = new HashMap<>();
public Test() {
for (Class clazz : classes) {
sets.put(clazz, new HashSet<>());
}
}
public void add(Interface value) {
Set<Interface> set = sets.get(value.getClass());
if (set != null) {
set.add(value);
} else {
throw new IllegalArgumentException();
}
}
}