我想用两个简单的方法创建一个类 - 第一个注册需要处理的类型。第二个将处理所有已注册的类型。我遇到的问题是我想注册/处理的类有一定的限制——它们必须是实现和接口的枚举
我不太清楚如何定义将用于存储注册类型的集合。我的代码的简化版本是:
public class Example {
interface MyType {
// Add methods here
}
private List<what-goes-here?> store = new ArrayList<>();
public <T extends Enum<?> & MyType> void registerType(@Nonnull Class<T> type) {
store.add(type);
}
public void processAll() {
for (T t : store) { // Where do I define T?
// process t
}
}
}
Run Code Online (Sandbox Code Playgroud)
这个怎么样?
public class Example {
interface MyType {
// Add methods here
}
// v--- save it as enum class
private List<Class<? extends Enum<?>>> store = new ArrayList<>();
public <T extends Enum<?> & MyType> void registerType(@Nonnull Class<T> type) {
store.add(type);
}
public void processAll() {
// v--- iterate each enum type
for (Class<? extends Enum<?>> type : store) {
Enum<?>[] constants = type.getEnumConstants();
for (Enum<?> constant : constants) {
//v--- downcasting to the special interface
MyType current = (MyType) constant;
// TODO
}
}
}
}
Run Code Online (Sandbox Code Playgroud)