Catching ArrayStoreException at Compile-time

后端 未结 4 1680
悲哀的现实
悲哀的现实 2021-01-20 22:40

Consider the following test of Java\'s ArrayList#toArray method. Note that I borrowed the code from this helpful answer.

public class GenericTest {
         


        
4条回答
  •  北恋
    北恋 (楼主)
    2021-01-20 23:25

    List#toArray(T[]) is a generic method declared as

     T[] toArray(T[] a);
    

    So the type argument is either inferred from the type of the given array or with the notation prefixing the method invocation.

    So you could do

    String[] baz = foo.toArray(new String[10]); // doesn't compile
    

    But I think that's the best you could do.

    But in that sense, you can clearly see that Integer doesn't match String (or vice-versa).

    Note that this is a documented exception

    ArrayStoreException - if the runtime type of the specified array is not a supertype of the runtime type of every element in this list

    So I don't think you should be trying to find it at compile time.

提交回复
热议问题