Is it possible to force an interface to be implemented only by enums?

Unfortunately you can't really do this at compile-time. You can give hints at this by requiring methods like ordinal() and name() or you can check it at runtime.

Regarding "I can't trust the library users": as long as you document the requirement in the interfaces JavaDoc, anyone who doesn't follow it gets what he pays for.

That's exactly the same as if someone didn't implement equals() and hashCode() correctly: the compiler doesn't enforce it, but if you break it, then classes that depend on them break as well.

The closest you can get is probably something like this:

public interface EnumInterface<E extends Enum<E>> {
}

where the implementation would look like this:

public enum MyInterfaceImpl implements EnumInterface<MyInterfaceImpl> {
  FOO,
  BAR;
}

It's just another hint, since a "malicious" developer could still build a class like this:

class NotAnEnum implements EnumInterface<MyInterfaceImpl> {
}

All in all, there will always be ways to mis-use any library. The library authors goal is to make it easier to use the library correctly than it is to use the library incorrectly. You don't need to make it impossible to use it incorrectly.


I'd like to know if it's possible to force an interface to be implemented by an enum.

No, it is not. Interfaces can be implemented by any class and you cannot force the user of your library to use an enum.

Tags:

Java

Enums