본문 바로가기
Java 배우기

Erasure of Generic Methods 제네릭 메소드의 이레이저

by 노화방지 Anti-aging Hairstyle 2016. 1. 24.
반응형


제네릭 메소드의 이레이저 Erasure of Generic Methods


자바 컴파일러는 또한 제네릭 메소드 아규먼트에 있는 타입 패러미터를 지웁니다.
다름 제네릭 메소드를 검토하십시오:
The Java compiler also erases type parameters in generic method arguments. Consider the following generic method:

// Counts the number of occurrences of elem in anArray.
//
public static <T> int count(T[] anArray, T elem) {
    int cnt = 0;
    for (T e : anArray)
        if (e.equals(elem))
            ++cnt;
        return cnt;
}

Because T is unbounded, the Java compiler replaces it with Object:

public static int count(Object[] anArray, Object elem) {
    int cnt = 0;
    for (Object e : anArray)
        if (e.equals(elem))
            ++cnt;
        return cnt;
}

Suppose the following classes are defined:

class Shape { /* ... */ }
class Circle extends Shape { /* ... */ }
class Rectangle extends Shape { /* ... */ }

You can write a generic method to draw different shapes:

public static <T extends Shape> void draw(T shape) { /* ... */ }

The Java compiler replaces T with Shape:

public static void draw(Shape shape) { /* ... */ } 


반응형

댓글