Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tricky static generic method with generic return type which itself could be a generic

Tags:

java

generics

I have a class as follows:

public class MyConverter {
    public <T> T convert (Object o, String typeidentifier, T dummy)
    {
         ... do some conversions such as a java array to an ArrayList or vice versa
         ... based on a typeidentifier syntax similar to Class.getName() but which
         ... embeds information about generic subtypes
    }
}

and want to be able to do something general like this:

int[] ar = {...};
ArrayList<Integer> dummy = null;
Integer elem = MyConverter.convert(ar, "java.util.ArrayList<Integer>", dummy)
                  .get(15);

That is, the T in convert may itself be a generic instance, and I found that to get this goal to work, I have to pass a fully typed dummy, as ArrayList.class won't give the java compiler enough information that it is an ArrayList<Integer> if I used Class<T> dummycls instead of T dummy.

Am I missing something? Is there a way to both write and invoke convert without requiring a dummy?

like image 741
Andy Nuss Avatar asked Jun 26 '12 17:06

Andy Nuss


1 Answers

Specify the type on your call, rather than letting java infer the type:

Integer elem = MyConverter.<ArrayList<Integer>>convert(ar, "java.util.ArrayList<Integer>");

This link describes this (cool) syntax.

like image 139
Bohemian Avatar answered Oct 10 '22 21:10

Bohemian