[concurrency-interest] [HS] why creation of array of parametrized type is unsafe

Rémi Forax forax at univ-mlv.fr
Fri Nov 10 03:51:21 EST 2006


Dhanji R. Prasanna a écrit :
> A similar problem exists with parameterized collections--at runtime I 
> can add objects not of a reified type via reflection (unless using a 
> checkedSet or list..which throws CCE).
> Is this true?
Reflection and generics doesn't play well together, by example, the 
following code is
safe but generates a CCE at le last line.

public static void main(String[] args) throws IllegalAccessException, 
InvocationTargetException, NoSuchMethodException {
      ArrayList<String> list=new ArrayList<String>();
     
      List.class.getMethod("add",Object.class).invoke(list,3);
     
      list.get(0).charAt(0);
}

so it is another problem.

Rémi

>
> On 11/10/06, *Joshua Bloch* <josh at bloch.us <mailto:josh at bloch.us>> wrote:
>
>     Rémi,
>
>     Because the the array that is created is generally *not* an array
>     of T (the type parameter), but of its bound.  Automatically
>     generated casts at the call site can fail.  Run this program
>     (which compiles with a warning) and you'll get the idea.  The
>     program was written by Peter van der Ahe:
>
>
>
>     public class GenericVarargs {
>        static <T> T[] m1(T t1, T t2) {
>            return m2(t1, t2);
>        }
>        static <T> T[] m2(T... args) {
>            return args;
>        }
>        public static void main(String... args) {
>            String[] strings = m1("bad", "karma");
>
>        }
>     }
>
>
>
>     On 11/9/06, *Rémi Forax * < forax at univ-mlv.fr
>     <mailto:forax at univ-mlv.fr>> wrote:
>
>         It's a totally HS question, but i know that some Java gurus
>         listen that
>         list.
>
>         It's perhaps a stupid question, but i don't see why array of
>         parametrized type
>         is unsafe.
>
>         see my blog on that :
>         http://weblogs.java.net/blog/forax/archive/2006/11/why_array_of_pa.html
>
>         Rémi
>
>         _______________________________________________
>         Concurrency-interest mailing list
>         Concurrency-interest at altair.cs.oswego.edu
>         <mailto:Concurrency-interest at altair.cs.oswego.edu>
>         http://altair.cs.oswego.edu/mailman/listinfo/concurrency-interest
>         <http://altair.cs.oswego.edu/mailman/listinfo/concurrency-interest>
>
>
>
>     _______________________________________________
>     Concurrency-interest mailing list
>     Concurrency-interest at altair.cs.oswego.edu
>     <mailto:Concurrency-interest at altair.cs.oswego.edu>
>     http://altair.cs.oswego.edu/mailman/listinfo/concurrency-interest
>
>
>




More information about the Concurrency-interest mailing list