简体   繁体   中英

Type erasure unexpected behavior in Java

According to Java's documentation on Type Erasure and Bounded Type Parameters , I understand that in the code example below both versions of doStuff() will have the same erasure and, therefore, won't compile. My goal is to overload doStuff() in order to receive collections of ClassOne and ClassTwo .

import java.util.List;

class Example {
  class ClassOne {
  }

  class ClassTwo {
  }

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

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

Mechanics for type erasure include the following step:

· Replace all type parameters in generic types with their bounds or Object if the type parameters are unbounded. The produced bytecode, therefore, contains only ordinary classes, interfaces, and methods.

Therefore, I should be able to apply a bound and then it would compile because now the type erased version of doStuff is overloaded with two different signatures (the 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 actually doesn't 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 anyone explain this to me?

The problem is that List<U> will be reduced to just List in both your methods. (You can't have List<ClassOne> or List<Object> left after erasure.)

The passage you quote means that it is ok to have 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 generic arguments will be replaced by ClassOne and ClassTwo respectively, which works just fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM