pcjuzer
pcjuzer

Reputation: 2824

Java method returns an enum which implements an interface

How can I specify that a Java method returns an enum which implements an interface? This method is given:

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?

Upvotes: 4

Views: 226

Answers (3)

Amit Deshpande
Amit Deshpande

Reputation: 19185

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 More Simpler Version

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

Upvotes: 3

Vala
Vala

Reputation: 5674

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

Upvotes: 1

Jo&#227;o Mendes
Jo&#227;o Mendes

Reputation: 1425

If someMethod expects a Class<T> parameter, where T extends Enum<T> & SomeInterface, then that's what you need to return from anotherMethod. And since you don't have anything in the parenthesis in your desired call, I would say simply:

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

Upvotes: 3

Related Questions