How to declare an object of class <?> Such that it is an Enum AND an interface in Java

I have a utility class that needs to work with a generic class, but needs to be limited to those that are enumerated and implement a specific interface.

// These two work
Class<? extends Enum<?>> enumClass;
Class<? extends MyInterface> interfaceClass;

// This is what I want but does not work
Class<? extends MyInterface & Enum<?>> enumAndInterfaceClass;

      

For generics I can successfully use this

public class MyClass<T extends Enum<T> & MyInterface> {
    public MyClass(Class<T> theClass) {
        ...
    }
}

      

However, I cannot use Generics everywhere and must declare it separately. I'm not sure if this is possible.
So my question boils down to how can I declare a member variable with these constraints?

So now MyClass is a singleton, then the enum / interface is updated as needed. The return values ​​of its operations will change depending on which enumeration it is given. I wish it didn't have generics as this would require creating a new instance for every change to the enum. There is a lot of code out there using it, so deviation from singleton will not be approved. Thus, the link must be preserved. I suppose I could only fulfill the requirement of the interface and then check in the setter method that it is an enum throwing an exception, but this is not ideal.

Edit (updated question and added in more detail)

+3


source to share


2 answers


As far as I remember, you can only declare intersection types (that's what it creates &

) for class and method type parameters. You cannot declare a local variable with an intersection type directly; you can create such variables using a class parameter or method type as seen in the answer to the milk plusellella question.



See the JLS link in this answer to a similar question: fooobar.com/questions/87372 / ...

+2


source


This should work:

public interface MyInterface {

    void foo();
}

public final class Utils {

    public static <E extends Enum<E> & MyInterface> void doWork(Class<E> clazz) {
        for(E enumConstant : clazz.getEnumConstants) {
            enumConstant.foo();
        }
    }
}

      



EDIT I didn't notice your line about using the captured type as a local variable. You can of course use this throughout the body of a parameterized method, see the revised snippet above.

+2


source







All Articles