Jump to content

Talk:Generics in Java

Page contents not supported in other languages.
From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Matthew0028 (talk | contribs) at 07:52, 11 December 2006 (Reflection example not correct: Clarified example). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

Reflection example not correct

I removed the following text, as it isn't correct:

It is possible to work around this limitation to some extent by using Java's reflection mechanisms. If an instance of class T is available, one can obtain from that object the Class object corresponding to T and use java.lang.reflect.Array.newInstance to create the array.

Let's say I have toArray(List<T> list) with at least one element. I call this using a List&ltNumber&gt containing Integers and Floats. Array.newInstance() using my first element of my list (which an instance of class Number) I end up with an array of type Integer[]. When I try to add a Float to the array, my program will fail with an error.

Now, it is possible if I pass in a Class<T> as in toArray(List<T> list, Class<T> clazz). Calling Array.newInstance(clazz, list.length()) will work just fine. However, I don't think it's worth mentioning this in the actual article. —Matthew0028 07:50, 11 December 2006 (UTC)[reply]