How can I migrate a Java enumeration and still iterate over it?

How can I get an abstract enumeration or some kind of basic enumeration?

In my general code, I would like to have an idea of ​​the enum element, MyItems, without binding myself to a specific enumeration. Then in each of my projects I would have a specific implementation.

eg. Common code

public interface MyItems {
    // Marker interface
}

Project A

public enum Items implements MyItems {
     RED_CAR, BLUE_CAR, GREEN_CAR;
}

Project B

public enum Items implements MyItems {
    BROWN_TREE, GREEN_TREE;
}

This seems to work, but in my general code, I cannot write a loop over my interface enumeration, since it is not an enumeration. In my general code, I would like to write

for (MyItems item : MyItems.values())
    doSomething(item);

but I cannot, because my interface is just a marker interface, and it does not have .values ​​().

Any suggestions are greatly appreciated. I do not know if I am trying completely wrong.

+3
3

, values() . , , .

:

public interface MyItemsFactory<T extends MyItems>
{
    Iterable<T> values();
}

- ,

public class EnumFactory<T extends Enum<T> & MyItems>
    implements MyItemsFactory<T>
{
    private final Class<T> clazz;

    public EnumFactory(Class<T> clazz)
    {
        this.clazz = clazz;
    }

    public Iterable<T> values()
    {
        return EnumSet.allOf(clazz);
    }
}

, . :

for(MyItems item : MyItems.values())
    doSomething(item);

MyItems , ? , MyItems.

+8
+1
0

Source: https://habr.com/ru/post/1720661/


All Articles