Type of generated Java type not used in parameters

In the java library, I came across a method that uses a common return type, which is not used in the parameters:

<T extends ResponseCallBack> T sendData(@Nonnull final OrderIf checkoutOrder, @Nullable final List<NameValueIf> ccParmList) throws Exception; 

( ResponseCallBack is the interface here)

What is the difference with this signature:

 ResponseCallBack sendData(@Nonnull final OrderIf checkoutOrder, @Nullable final List<NameValueIf> ccParmList) 
+7
java generics
source share
2 answers

The difference is that you can use this special version for a chain of methods.

Check out this 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 to bar1 is possible only because of <T extends MyFoo> , without it, it should be done:

 final MyBar bar1 = (MyBar) new MyBar().foo(); 

Unfortunately, at least with Java 7, the end of the compiler output ends here, so you cannot do

 new MyBar().foo().bar(); 
+5
source share

The difference is in the first parameter, the caller can limit the type that is returned to some extent, while for the second you only know that you will receive a ResponseCallBack , and you will have to do the translation if you want a subtype.

For example, from the first you can do:

 Subtype temp = caller.<subtype> sendData(...); // Can also skip explicitly passing the type parameter too 

instead

 Subtype temp = (Subtype) caller.sendData(...); 

Thus, I believe this is a way to provide type safety during a call, and also allows the caller to exclude casts from his code.

+1
source share

All Articles