I'd like to know if it's possible to force an interface to be implemented by an enum.
I have the following interface:
public interface MobileApplication {
String name();
}
This should be implemented by an enum because i need garantee on the uniqueness of the name. As i am designing a library i can't trust the library users, and without an unique name, my library will not work at all.
I can do without with security, just wonder if it's possible. Thanks
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With