Changes between Version 2 and Version 3 of ExampleUsingOwnConceteTypes


Ignore:
Timestamp:
Oct 6, 2006, 5:09:28 PM (20 years ago)
Author:
lauer
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • ExampleUsingOwnConceteTypes

    v2 v3  
    11== Using own concete types ==
    22
    3 [|Special case: Using own types in Collections and Maps.] Java's type erasure in action!
     3[http://delight.opendfki.de/wiki/ExampleUsingOwnConceteTypes#UsingowntypesinCollectionsandMaps Special case: Using own types in Collections and Maps.] Java's type erasure in action!
    44
    55=== Server side ===
    66
     7We want to use the type {{{Param}}} in our API. Normally, this will cause an error message. See how we can make this type
     8XML-RPC compliant with only a few lines of code:
    79
    810{{{
    … …  
    1618public class Impl implements Api
    1719{
    18     public Param returnParam() { return new ParamImpl( ... ); }
     20    public Param returnParam() { return createParam( ... ); }
    1921   
    20     void passAsParameter( Param p ) {}
     22    void passAsParameter( Param p ) { doSomethingWith( p ); }
    2123}
    22 
    2324}}}
    2425
    … …  
    6970== Using own types in Collections and Maps ==
    7071
     72When using generics in the API methods, java runs a so called type erasure on all generic types, reducing a Collection<Param> to a simple Collection.
     73The runtime system cannot determine the content type of this collection unless the user places an extra hint using the @Contains annotation.
     74
     75{{{
     76// DOES NOT WORK: Map<String,Param> will be reduced to Map, Collection<Param> will be reduced to Collection
     77public interface Api
     78{
     79    Map<String,Param> returnMyParamInMap();
     80   
     81    void passManyParams( Collection<Param> params );
     82}
     83}}}
     84
     85Place a @Contains in front of the method to annotate a return type. Place it before a formal parameter
     86to annotate method parameters.
     87{{{
     88// WORKS!
     89public interface Api
     90{
     91    @Contains(Param.class)
     92    Map<String,Param> returnMyParamInMap();
     93   
     94    void passManyParams( @Contains(Param.class)
     95                         Collection<Param> params );
     96}
     97}}}
     98
     99== Client Side ==
     100Now remote clients can also use Collections and Maps containing own types:
     101{{{
     102Api remote_api = XmlRpc.createClient( Api.class, "handlerId", host, port );
     103
     104Map<String,Param> map = remote_api.returnMyParamInMap();
     105for( Param p : map.values() )
     106{
     107  ...
     108}
     109
     110remote_api.passManyParams( Collections.asList( new Param[]{new Param()} ) );
     111...
     112}}}