Java generics SuppressWarnings(“unchecked”) mystery

前端 未结 4 1410
盖世英雄少女心
盖世英雄少女心 2021-02-14 03:28

Why does code alternative(1) compile without warnings, and code alternative(2) produce an \"unchecked cast\" warning?

Common for both:

class Foo         


        
4条回答
  •  长情又很酷
    2021-02-14 03:53

    I was able to reproduce the behavior with this simplified setup:

    class Bar {
       @SuppressWarnings("unchecked")
       Bar() {
          T[]dummy = (T[]) EMPTY_ARRAY;
       }
    
       private static final Object [] EMPTY_ARRAY = {};
    }
    

    As Brian suggested, it seems to be a bug in the compiler. Additionally, this behavior is restricted to Arrays - replacing the EMPTY_ARRAY with an Object and casting it to a T does not issue a warning as expected.

    java version "1.7.0_09"
    Java(TM) SE Runtime Environment (build 1.7.0_09-b05)
    Java HotSpot(TM) 64-Bit Server VM (build 23.5-b02, mixed mode)
    

提交回复
热议问题