2

I have is an interface which is meant only to be overridden by enums -

interface Parent{
    int someMethod(); 
}

and method in which I am going to pass an implementor of Parent. this method wants to restrict users to pass any other implementor other than enum -

public static <T extends Enum<? extends Parent>> T fromInt(Class<T> enumClass){}

Now the issue is

  1. the enum signature is unclean plus using ?.
  2. In order to access someMethod of parent class will need to be type casted in the method. If we like to access it like this -

    Arrays.stream(enumClass.getEnumConstants())
                .filter(ev -> ((Parent)ev).someMethod() == someVal)
                .findFirst().get();
    

Is there a better way of creating signature of this method to solve these issues?

Mohammad Adnan
  • 6,527
  • 6
  • 29
  • 47

1 Answers1

5

You can't force implementors of an interface to only be enums.

However, you can achieve what you want by saying that the type T should be an enum type, with T extends Enum<T>, and a Parent type, with & Parent. & is used to declare an intersection of multiple interfaces. It makes sure that in the method, T can be bound to Enum and Parent.

This would be an implementation:

public static <T extends Enum<T> & Parent> T fromInt(Class<T> enumClass) {
    return Arrays.stream(enumClass.getEnumConstants())
                 .filter(ev -> ev.someMethod() == 1)
                 .findFirst()
                 .get();
}
Tunaki
  • 132,869
  • 46
  • 340
  • 423