Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JDK 1.7 breaks backward compatibility? (generics)

I've found similar topics, but overly complicated and not quite the same. So the thing is. Here's the(minimal) code which is fine on 1.6, but doesn't compile with 1.7 javac.

public class Test {
    private static class A<T>{};
    private static class B{};
    private static class C{};

    B doSomething(A<B> arg){
        return new B();
    }

    C doSomething(A<C> arg){
        return new C();
    }
}

On 1.7 the error is this:

java: name clash: doSomething(Test.A<Test.C>) and doSomething(Test.A<Test.B>) have the same erasure

I understand the type erasure and why it's a wrong code. I just don't understand why we can have this code in our project compiling and running in 1.6, when 1.7 have problems with it. What is wrong? Is it a bug in 1.6 compiler that it allows us to do so? Is it possible to make it work in 1.7 other than rewriting?

  • JDK1.6 javac version: 1.6.0_43
  • JDK1.7 javac version: 1.7.0_25
like image 537
NeplatnyUdaj Avatar asked Sep 04 '13 12:09

NeplatnyUdaj


2 Answers

You're quite right, under JLS3 this code should never have compiled and this was a bug in 1.6.

For the release of 1.7 much of the underlying type system was updated and this bug was fixed, the result is better type handling at the cost of some backward compatibility issues.

As for getting it to work in 1.7, I believe re-factoring is your only option.

like image 151
StuPointerException Avatar answered Oct 10 '22 19:10

StuPointerException


It is one of the bugs in javac that have been fixed in Java 7 - you can find more information in the release notes. I'm afraid your only option is to rewrite that code if you want to switch to Java 7.

Area: Tools
Synopsis: A Class Cannot Define Two Methods with the Same Erased Signature but Two Different Return Types
Description: A class cannot define two methods with the same erased signature, regardless of whether the return types are the same or not. This follows from the JLS, Java SE 7 Edition, section 8.4.8.3. The JDK 6 compiler allows methods with the same erased signature but different return types; this behavior is incorrect and has been fixed in JDK 7.
Example:

class A {
    int m(List<String> ls) { return 0; }
   long m(List<Integer> ls) { return 1; }
}

This code compiles under JDK 5.0 and JDK 6, and is rejected under JDK 7.

like image 26
assylias Avatar answered Oct 10 '22 20:10

assylias