How to create a generic type that only allow a specific class to extends/implements it

Viewed 40

For example, I want to create a generic interface IEnum and make sure that every IEnum instance is also an enum constant, in other words, only enum type can implement IEnum. Does java support such feature or can it be achieved by any workaround? Can it be achieved by recursive Bounded Type Parameters?

1 Answers

You can use a recursive bounded and a union type parameter, to enforce that the the passed generic class is an Enum and implements IEnum:

public interface IEnum<E extends Enum<E> & IEnum<E>> {}

Note: the order matters, so the first type can either be a class or interface, but everything that follows it must be an interface.

You can then use it like this:

public enum Foo implements IEnum<Foo> {}

Sadly, you can't force the implementing class to pass itself as a type parameter, e.g. this would work:

public class Bar implements IEnum<Foo> {}

Also you can't constrain the implementation to not use raw types, e.g. this would also work:

public class Baz implements IEnum {}
Related