The Java method returns an enumeration that implements the interface.

How can I indicate that the Java method returns an enumeration that implements the interface? This method is set:

public <T extends Enum<T> & SomeInterface> void someMethod(Class<T> type) { } 

And I want to do:

 someMethod(anotherMethod()); 

What should be the signature of anotherMethod ?

+4
source share
3 answers

If someMethod expects a Class<T> parameter, where T extends Enum<T> & SomeInterface , then what you need to return from anotherMethod . And since you do not have anything in brackets for your desired call, I would say simply:

public Class<T extends Enum<T> & SomeInterface> anotherMethod()

+3
source

The correct implementation should be

 <T extends Enum<? extends T> & SomeInterface> void someMethod(Class<T> type); <T extends Enum<? extends T> & SomeInterface> Class<T> anotherMethod(); 

Please check more fun with wildcards

Or a simpler version

 public class Example<T extends Enum<T> & SomeInterface> { public void someMethod(Class<T> type) {} public Class<T> anotherMethod() {} } 
+3
source

anotherMethod just needs to return a Class , it could be the exact class that you have in mind that extends your enum and interface, or just a wildcard Class<?> (although you will have compile-time warnings). If you want to avoid warnings, the return type must be Class<T> with the definition of generics T , as in the method you call.

+1
source

Source: https://habr.com/ru/post/1435479/


All Articles