Ankit Singodia
Ankit Singodia

Reputation: 641

Generic Array Without Reflection

I already read some of the answers following which I know 1 of the technique of creating a generic array is using reflection but what of I write the below generic method for creating an array? Is this potentially dangerous in any way?

public <E> E[] getArray(int size, Class<E> e) { 

          E[] arr = (E[])new Object[size];    
          return arr;    

}

Upvotes: 2

Views: 85

Answers (2)

Stephan Herrmann
Stephan Herrmann

Reputation: 8178

Arrays and generics are concepts from two different eras of Java, which are not designed for being mixed. If you want typesafe genericity, why not use ArrayList instead of the array?

Upvotes: 0

Eran
Eran

Reputation: 393956

It simply doesn't work.

The compiler will allow you to write:

String[] sarr = new YourClass().getArray(10,String.class);

but in runtime you'll get an exception:

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;

Upvotes: 3

Related Questions