How can I invoke name() inside an interface for an Enum?

Viewed 34

I defined an interface for enum types.

interface MyInterface<E extends Enum<E> & MyInterface<E>> {
}

// e.g.
enum MyEnum implements MyInterface<MyEnum> {
}

Now I want to access name() method from a method defined in above interface.

interface MyInterface<E extends Enum<E> & MyInterface<E>> {

    default void doSomeWithEnumName() {
        // How can I access #name() method in here?
    }
}
1 Answers

You can cast this to an Enum<?> and just access name().

System.out.println(((Enum<?>) this).name());

However, with the current set up, it is in fact possible for one to be naughty and create a non-enum class that implements your interface:

enum Bar implements MyInterface<Bar> {}
class Foo implements MyInterface<Bar> {}

Therefore, I would advise that you check the type of this first:

if (this instanceof Enum<?> enumThis) {
    System.out.println(enumThis.name());
} else {
    throw new RuntimeException("Only enums can implement this interface!");
}

(I can't think of how you would limit the interface to be only implementable only for enums - there are no "self" types in Java)

Related