Java generic return type is not used in parameter
•
Java
In the Java library, I encountered a method that uses a generic return type, which is not used in any way in the parameters:
<T extends ResponseCallBack> T sendData(@Nonnull final OrderIf checkoutOrder,@Nullable final List<NameValueIf> ccParmList) throws Exception;
(responsecallback is an interface here)
What is the difference between this signature:
ResponseCallBack sendData(@Nonnull final OrderIf checkoutOrder,@Nullable final List<NameValueIf> ccParmList)
Solution
The difference is that you can use this special version for method linking
Check this sample program:
public class MyFoo { public <T extends MyFoo> T foo(){ System.out.println("foo"); return (T) this; } static class MyBar extends MyFoo{ public <T extends MyBar> T bar(){ System.out.println("bar"); return (T) this; } } public static void main(String[] args) { final MyFoo foo = new MyFoo().foo(); final MyBar bar1 = new MyBar().foo(); final MyBar bar2 = new MyBar().bar(); } }
The assignment of bar1 variable is only possible, because < T extends myfoo >, without it, there must be a cast:
final MyBar bar1 = (MyBar) new MyBar().foo();
Unfortunately, at least in Java 7, compiler inference ends here, so you can't
new MyBar().foo().bar();
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码