Java: Security Type: A generic array A is created for the varargs parameter

Possible duplicate:
Is it possible to solve the problem? Is the generated array T created for the varargs parameter? Compiler Warning?

We believe that this is given:

interface A<T> { /*...*/ } interface B<T> extends A<T> { /*...*/ } class C { /*...*/ } void foo(A<T>... a) { /*...*/ } 

Now another code wants to use foo :

 B<C> b1 /* = ... */; B<C> b2 /* = ... */; foo(b1, b2); 

It gives me a warning

 Type safety : A generic array of A is created for a varargs parameter 

So, I changed the call to this:

 foo((A<C>) b1, (A<C>) b2); 

It still gives me the same warning.

Why? How can i fix this?

+7
java casting variadic-functions
source share
3 answers

All you really can do is suppress this warning with @SuppressWarnings("unchecked") . Java 7 will eliminate this warning for client code by moving it to the declaration foo(A... a) , and not to the call site. See Coin Design Proposal here .

+14
source share

Edit: The answer has been updated to reflect this question, updated to show that A is indeed shared.

I would think that A should be generic to get this error. Is A common in your project, but the code sample above leaves a general declaration?

If so, since A is generic, you cannot bypass the warning cleanly. Varargs are implemented using an array, and the array does not support shared arrays, as described here:

Java generics and varargs

+5
source share

You can try the following:

 <T> void foo(T... a) { /*...*/ } 
0
source share

All Articles