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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With