felix-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From David Bosschaert <david.bosscha...@gmail.com>
Subject Re: [Converter] Map -> Object with generics
Date Wed, 24 Aug 2016 17:39:41 GMT
BTW I'm just noticing that the generic type arguments are not yet used for
conversions to DTOs, if you have a test case or even a patch that would be
great :)

Cheers,

David

On 24 August 2016 at 18:38, David Bosschaert <david.bosschaert@gmail.com>
wrote:

> Hi David,
>
> The current converter implementation actually has (some) support for this
> already via the TypeReference-based APIs. Basically this generic
> information is preserved if you create a subclass for your type, and the
> way to do this is by creating an (anonymous) TypeReference subclass.
>
> You can find an example in the ConverterMapTest.testGenericMapConversion()
> [1]
>
> Basically what that test does is convert this map:
>   Map<Integer, String> m1 = Collections.singletonMap(42, "987654321");
> into a Map<String, Long>. So the number 42 needs to be converted into a
> String and the string "987654321" needs to be converted into a long.
>
> An anonymous TypeReference subclass is used to tell the converter to do
> this:
>   Map<String, Long> m2 = converter.convert(m1).to(new
> TypeReference<Map<String, Long>>(){});
>
> Then at then end of the test you'll see that the correct converted types
> are being converted to are asserted.
>
> So in your case you should be able to specify the conversion as:
>   TopDTO<BottomDTO> dto = converter.convert(someMap).to(new
> TypeReference<TopDTO<BottomDTO>>(){});
>
> Hope this works for you :) The implementation of TypeReference-based APIs
> isn't completely finished, so if you find an issue, let us know!
>
> Cheers,
>
> David
>
> [1] https://svn.apache.org/viewvc/felix/trunk/converter/
> src/test/java/org/apache/felix/converter/impl/ConverterMapTest.java?view=
> markup#l54
>
> On 24 August 2016 at 18:21, David Leangen <osgi@leangen.net> wrote:
>
>>
>> Hi!
>>
>> I’m having a bit of trouble, so am fishing for ideas. Maybe there is a
>> simple answer.
>>
>> If I convert from Map—>DTO, and the DTO has in its tree a generic field,
>> how can I tell the converter the correct type so that it does not get
>> converted as a Map?
>>
>> Example:
>>
>> BottomDTO {
>>   public String a;
>>   public String b;
>>
>> MiddleDTO<T> {
>>   public T bottom;
>> }
>>
>> TopDTO<T> {
>>   public MiddleDTO<T> middle;
>> }
>>
>> If I just do this, then Map is used for the value of bottom, which will
>> cause a ClassCastException sometime later during execution:
>>
>>   // Convert from Map to TopDTO<BottomDTO>
>>   converter.convert(someMap).to(TopDTO.class);
>>
>>
>> Thanks!
>> =David
>>
>>
>>
>

Mime
  • Unnamed multipart/alternative (inline, None, 0 bytes)
View raw message