Java generics SuppressWarnings(“unchecked”) mystery

前端 未结 4 1399
盖世英雄少女心
盖世英雄少女心 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 04:14

    It's a bug in both Oracle and OpenJDK 7 and 8.

    You can't (shouldn't) get compile warnings/errors from reordering declarations in a class.

    Runtime errors, yes; compiler errors, no.

    This is Bug 8016636 (thanks for filing it), but there's been no activity in over a year.

    Unfortunately, that is not uncommon in Oracle's bug tracker.


    Additional weirdness:

    • The warning is suppressed if EMPTY_ARRAY is not final.

    • Ironically, the warning is suppressed with if you initialize it with a non-array, e.g. Object EMPTY_ARRAY = new Object(). (But don't do that...)

提交回复
热议问题