규칙41) 오버로딩을할 때는 주의하라!

2015. 7. 21. 02:16Language/Java

반응형




제네릭 메카니즘 “Erasure"
Type Erasure

Generics were introduced to the Java language to provide tighter type checks at compile time and to support generic programming. To implement generics, the Java compiler applies type erasure to:

  • 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.
  • Insert type casts if necessary to preserve type safety.
  • Generate bridge methods to preserve polymorphism in extended generic types.
Type erasure ensures that no new classes are created for parameterized types; consequently, generics incur no runtime overhead.


Raw Types

raw type is the name of a generic class or interface without any type arguments. For example, given the generic Box class:

public class Box<T> {
    public void set(T t) { /* ... */ }
    // ...
}

To create a parameterized type of Box<T>, you supply an actual type argument for the formal type parameter T:

Box<Integer> intBox = new Box<>();


Row Type이 동일한 모든 제네릭 타입은 컴파일된 시점에서 모두가 동일한 타입으로 존재!

Test.java

public class Test<K, V> {
     public void f(K k) {
     }
     public void f(V v) {
     }
}


localhost:src terrypark$ javac Test.java
Test.java:5: error: name clash: f(V) and f(K) have the same erasure
public void f(V v) {
^
where V,K are type-variables:
V extends Object declared in class Test
K extends Object declared in class Test
1 error



반응형