A complex static universal method with a common return type, which in itself can be shared

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 in common:

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

That is, Tin convert can itself be a common instance, and I found that in order for this purpose to work, I have to pass a fully typed layout, since the ArrayList.classjava compiler will not give enough information what ArrayList<Integer>if I used Class<T> dummyclsinstead T dummy.

Am I missing something? Is there a way for both recording and invoking conversion without using a dummy?

+7
source share
3 answers

Specify the type of your call, instead of allowing java to infer the type:

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

() .

+10

Arrays.asList, ArrayList.

:

 public static <T> List<T> asList(T... a) {
    ArrayList<T> arr = new ArrayList<T>();
    for (T item: a) {
        arr.add(item);
    }
    return arr;
}
+4
public class MyConverter {
public static void main(String[] args) {
    Integer i = MyConverter.convert();
    System.out.println(i);
}

@SuppressWarnings("unchecked")
private static <T> T convert() {
    Integer i = new Integer(10);
    return (T)i;
}

}

0
source

All Articles