Is it possible to use wildcards as an attribute itself and not as a type parameter?

public void doSomething(<? extends Context> myObject){


}

I want to make sure that my object extends Context and also implements a certain interface.

Using wildcards as a return type is valid but using it as an attribute seems to not work

public <? extends MyClass> validMethod(){


}
有帮助吗?

解决方案

Yes it's possible, you have to define it before the return type.

public <T extends MyClass> void myMethod(T param);

其他提示

You don't explicitly state (for your case) which is the interface and which is the class, but if you wanted to have a generic type bound to both extending a class and an interface, this would be the general form for it.

public <T extends Number & Comparable<T>> T findNumber(List<T> elements) { }

Number is an abstract class; Comparable is an interface. I believe what you have to specify them in this order - concrete before interface.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top