ArrayFactory SAM type / toArray

Joshua Bloch josh at
Thu Sep 20 08:37:08 PDT 2012


On Thu, Sep 20, 2012 at 1:13 AM, Remi Forax <forax at> wrote:

> On 09/20/2012 08:49 AM, Joshua Bloch wrote:
>> Donald,
>> I believe this does work, with one caveat: if the type is generic, these
>> methods will return a generic array, which will generate an unchecked cast
>> warning.
> No, with the current JLS rules, you can't create a Class of T with a
> generic T without a warning.
> List<String>.class doesn't compile and foo = new ArrayList<String>(),
> foo.getClass() returns a Class<ArrayList>
> (and not a Class>ArrayList<T>>), so you can't create a generic array
> without having an unsafe cast somewhere.

Umm... Yeah. That's exactly what I said. It works except that you have to
use raw types if the type you're trying to get an empty array of is
generic, in which case you'll get unchecked cast warnings.  I suspect this
won't be a common case, but it won't be vanishingly rare either.

> But there is an issue with Class that represents a primitive type,
> int.class is typed Class<Integer>, so either emptyArray() should return an
> Integer[] or
> it should throw an exception.

Probably a non-issue, since Java doesn't support primitives as type
parameters (sadly).


More information about the lambda-libs-spec-observers mailing list