Java 8 autoboxing + generics: different behaviour with variable vs. method

前端 未结 4 849
日久生厌
日久生厌 2021-02-07 07:43

I found a piece of code that after switching from Java 7 to Java 8 stopped compiling. It does not feature any of the new Java 8 stuff like lambda or streams.

I narrowed

4条回答
  •  没有蜡笔的小新
    2021-02-07 07:55

    This seems to be a known issue of the Oracle compiler: Bug ID: JDK-8162708

    Quote:

    A DESCRIPTION OF THE PROBLEM :
    If you have a method in a generic class declared as follow:

    class Foo {
      public T getValue() {
        // returns a value ...
      }
    }
    

    and you call the method above inside a ternary operator as follow

    Foo foo = new Foo<>();
    Float f = new Random().nextBoolean() ? foo.getValue() : 0f;
    

    you get a syntax error from the javac 1.8 compiler.

    But the code above compiles with no errors and warnings with both javac 1.7 and 1.9.

    Resolution: Unresolved

    Affected Versions: 8

    From the Comments:

    This issue is only applicable to 8u, there is no issue in 7 and 9

提交回复
热议问题