How to convert generic list to generic array without reflection? Type parameter 'V' cannot be instantiated directl

Viewed 153

Here is simplified code example

 public V[] values() {
        List<V> values = pojo.getValues();

        return ; // values to array
    }

Signature of a method asking for V[] return type, but I got a List. Is it possible to convert List to V[] without reflection API?

I cant use values.toArray(new V[0]) or populate the array by myself because of error - "Type parameter 'V' cannot be instantiated directl"

1 Answers

You can do it without reflection using List::toArray(T[] a) method because you need to specify a certain type of an array as long as you cannot instantiate a generic array (new V[]):

public V[] values(V[] array) {
    List<V> values = pojo.getValues();
    return values.toArray(array);
}
Integer[] values = values(new Integer[0]);      // usage

It means you can perform the conversion directly and no such method is not needed (assuming there is no additional logics worth to encapsulate involved):

Integer[] values = pojo.getValues().toArray(new Integer[0]);
Related