2013-07-15 3 views
4

내 게임 엔진에는 많은 하위 클래스 (예 : Player, Cube, Camera 등)가있는 Entity 개체 목록이 있습니다. 내가 Class 객체를 전달하고 같은 클래스의 목록으로 끝내는 메소드를 원합니다. 내가 말하고 싶으면 이런 식으로 뭔가 : 지금까지매우 구체적인 Java 제네릭 문제 - 메서드에 전달 된 동일한 형식을 반환하는 방법?

List<Box> boxes = getEntities(Box.class); 

I가이 : 있어야 목록에서 각 인스턴스를 의미 Entity s의 목록을 반환

public List<Entity> getEntities(Class<? extends Entity> t) { 
    ArrayList<Entity> list = new ArrayList<>(); 

    for (Entity e : entities) { 
     if (e.getClass() == t) { 
      list.add(e); 
     } 
    } 

    return Collections.unmodifiableList(list); 
} 

그러나 물론

Box 클래스로 캐스트. Java에서 올바르게 수행 할 수있는 방법이 있습니까?

답변

3

나는 기존의 답변을 바탕으로 다음을 추천하지만, @SuppressWarnings을 피할 등

public <E extends Entity> ImmutableList<E> getEntities(Class<E> type) { 
    return ImmutableList.copyOf(Iterables.filter(entities, type)); 
} 
+0

놀랍습니다! 나는 비슷한 것을 썼지 만, E는 엔티티를 <>의 각 쌍으로 확장한다. 따라서 액세스 한정자 다음에 제네릭 형식을 넣으면됩니까? – Javawag

+1

@Javawag 정확히 - 메서드의 type 매개 변수를 선언 할 때 (수정 자 다음과 반환 유형 앞에) 상한 ('extends Entity') 만 지정하면됩니다. 일단 선언되면 다른 유형과 마찬가지로 참조 할 수 있습니다. –

1

메소드를 상한선으로 만듭니다.

public <T extends Entity> List<T> getEntities(Class<T> t) { 

그런 다음 코드의 다음 줄에 TEntity를 교체합니다.

ArrayList<T> list = new ArrayList<>; 

편집 @arshajii 코멘트에서 지적

, elist의 유형과 일치하는, T로 캐스트해야합니다.

public static List<? extends Entity> getEntities(Class<? extends Entity> t) { 
    ArrayList<Entity> list = new ArrayList<Entity>(); 

    for (Entity e : entities) { 
     if (e.getClass() == t) { 
      list.add(e); 
     } 
    } 

    return Collections.unmodifiableList(list); 
} 

를 다음 호출 할 수 있습니다 :

+2

당신은 캐스트'이 필요합니다 (T) e'를'for' 루프에 넣고'@SuppressWarnings ("unchecked")'와 함께 사용하기를 원할 수도 있습니다. – arshajii

+1

@arshajii Noooo !!! 't.cast'를 사용하십시오 (또는 이런 종류의 일을하지 마십시오). –

+0

@ TomHawtin-tackline이 경우 (경고 제외)의 차이점은 무엇입니까? – arshajii

-2

이 시도

List<Box> boxes = (List<Box>) getEntities(Box.class); 

지금 당신이 목록의 모든 단일 개체를 캐스팅 할 필요가 없습니다. 당신이 Guava를 사용하는 경우

public <E extends Entity> List<E> getEntities(Class<E> type) { 

    List<E> list = new ArrayList<>(); 

    for (Entity e : entities) { 
     if (type.isInstance(e)) { 
      list.add(type.cast(e)); 
     } 
    } 

    return Collections.unmodifiableList(list); 
} 

을 또는 :

관련 문제