2013-07-03 6 views
1

함수의 매개 변수에서 T를 검색하여 Vector의 유형을 정의하는 방법은 무엇입니까? 예 :함수 매개 변수의 템플릿

public void addPlot(String plotName, int minX, int maxX, 
     int minY, int maxY, PlotStyle plotStyle, Class<? extends Number> type) 
{ 
    Vector<type.class> dataset = new Vector<type.class>(); 
} 

답변

2

첫째, 자바, 그것은 "제네릭"가 아닌 "템플릿"(A C++ 용어)입니다.

다음으로 이름이 지정된 제네릭 형식 매개 변수를 사용하여 메서드를 일반화하고 사용하십시오. 당신이 그것을 사용하는 경우 <T>가되어 나타 곳

// generic declaration after public, before void 
public <T extends Number> void addPlot(String plotName, int minX, int maxX, 
     int minY, int maxY, PlotStyle plotStyle, Class<T> type) 
{ 
    Vector<T> dataset = new Vector<T>(); 
} 

<T extends Number>는, 다른 장소 (바운드 상단에) 당신의 제네릭 형식 매개 변수 선언이다.

관련 문제