Type erases unexpected behavior in Java

According to the Java documentation on Erasure Type and Restricted Type Parameters , I understand that in the code example below, both versions doStuff()

will have the same erasure and therefore will not compile. My goal is overloading doStuff()

to get collections ClassOne

andClassTwo

.

import java.util.List;

class Example {
  class ClassOne {
  }

  class ClassTwo {
  }

  public void doStuff(List<ClassOne> collection) {
  }

  public void doStuff(List<ClassTwo> collection) {
  }
}

      

The mechanics of type erasure involves the following step:

... Replace all type parameters in generic types with your constraints, or Object if the type parameters are not constrained. Thus, the resulting bytecode contains only regular classes, interfaces, and methods.

So I need to be able to apply the binding and then it gets compiled because now the type of the erased version of doStuff is overloaded with two different signatures (declared upper bounds). Example:

class Example {
  class ClassOne {
  }

  class ClassTwo {
  }

  public <U extends ClassOne> void doStuff(List<U> collection) {
  }

  public <U extends ClassTwo> void doStuff(List<U> collection) {
  }
}

      

This second example doesn't actually compile and gives the following error:

Error: (15, 36) java: name clash: doStuff (java.util.List) and doStuff (java.util.List) have the same erasure

Can someone explain this to me?

+3


source to share


1 answer


The problem is that it List<U>

will be reduced to just List

both of your methods. (You can't have List<ClassOne>

or List<Object>

left after erasing.)

The passage you are citing means that it should contain the following declaration:



class Example {
    class ClassOne {
    }

    class ClassTwo {
    }

    public <U extends ClassOne> void doStuff(U foo) {
    }

    public <U extends ClassTwo> void doStuff(U foo) {
    }
}

      

Here the general arguments will be replaced with ClassOne

and ClassTwo

accordingly, which works great.

+8


source







All Articles