2017-07-21 56 views
3

我想用两个简单的方法创建一个类 - 第一个注册需要处理的类型。第二个将处理所有已注册的类型。我得到的问题是,我想注册/过程的类有一定的限制 - 他们必须是实现和接口的枚举Java:如何定义一个实现接口的枚举集合

我不能完全解决如何定义将用于存储的集合注册类型。我的代码的简化版本是:

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 
     } 
    } 
} 
+3

您的代码不一致。在'register'中,你正在将'Class'对象存储到列表中,在'processAll'中,你期望'T'实例出来。除此之外,为什么这些对象是'enum's很重要?似乎没有对该财产的任何依赖,很难想象它将如何成为一个有用的财产。 – Holger

+0

@Holger嗨,我想他想处理所有枚举常量实例。 –

+2

@ holi-java提问者不应该要求我们猜测他们的意图。可能有很多更好的解决方案,具体取决于他们实际想要做的事情。 – Holger

回答

4

这个怎么样?

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 
      } 
     } 
    } 

} 
+0

在这种情况下只声明商店来保存“对象”,它是无关紧要的,因为你正在施放任何方式,尽我所能告诉 – Eugene

+0

@Eugene嗨,感谢您的反馈。但是如果将'Class'保存为'Object',它将在'processAll'中生成未经检查的警告,这就是为什么我将它保存为'Enum '而不是'MyType'的原因。我是对的,亲爱的? :) –

+0

我知道,但你可以明显地压制这一点......无论如何你并没有暴露'store'(它是私人的)。如果你要公开它,那么'MyType current =(MyType)常量'理论上仍然会失败,因为某些枚举实例不会实现'MyType'。 – Eugene

相关问题