Java: how to define a collection Enums that implements an interface

I want to create a class with two simple methods - the first one registers the type that needs to be processed. The second will handle all registered types. The problem is that the classes that I want to register / process have certain restrictions - they have to be enums that implement and interact

I am unable to work out how to define the collection that will be used to store the registered types. Simplified version of my code:

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


source to share


1 answer


How about this?



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

}

      

+4


source







All Articles