2
이전에 검사되지 않은 경고를 피하기 위해 멋진 포장을했는데, http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html 이상의 90 분 동안 보링 한 후에는 findMatch 메소드를 작성할 수 없으며 @SuppressWarnings (" 선택하지 않음 "). 파라미터 화 된 클래스는 컴파일시에는 알 수 없다. 모든 경우에 정합 가능한이 T.에 의해 구현되기 때문에다음에 표시되지 않는 경고를 피하십시오.
public interface Matchable<T>
{
public boolean matches(T toMatch);
}
public class PlaceForMatching
{
public static Object findMatch(Object toMatch, Object[] toSearch)
{
if(!(toMatch instanceof Matchable)) return null;
Matchable matchObj = (Matchable)toMatch;
Class<?> matchClass = matchObj.getClass();
for(Object obj : toSearch)
{
/**
* Check here verifies that the search list object we're about
* to check is the same class as the toMatch object.
* This means Matchable will work without a ClassCastException.
**/
if(matchClass.isInstance(obj) && matchObj.matches(obj))
return obj;
}
//Didn't find it
return null;
}
}
참고 코드가 작동
Apple implements Matchable<Apple>
Orange implements Matchable<Orange>
편집 : 몇 가지 테스트 코드
public static void main(String[] args)
{
Object[] randomList = createAppleArray();
Object apple = new Apple("Red");
Object match = findMatch(apple, randomList);
}
private static Object[] createAppleArray()
{
return new Object[] { new Apple("Pink"), new Apple("Red"), new Apple("Green") };
}
public class Apple implements Matchable<Apple>
{
String color;
public Apple(String color)
{
this.color = color;
}
public boolean matches(Apple apple)
{
return color.equals(apple.color);
}
}
이 올바른지를 추가하고 내가해야 이 질문에서 더 분명 해졌다. 매개 변수화되지 않은 유형을 사용하는 메소드 서명이 필요합니다 (공격 코드에 도달 할 때까지 손실되었습니다). 일반 메서드를 사용하여이 메서드에서 사용할 수 있도록 캐스팅 할 수있는 방법이 있다면 배우는 것이 좋습니다. ' 공공 정적를 확장> findMatch 개체 (toMatch 개체, 개체 [] toSearch) { 반환 findMatch ((T) toMatch ... 작동하지 않습니다 다음, 그러나 이것은 기본적인 아이디어 것 , (T []) toSearch); } ' –
'Matchable'과 'Matchable []'대신 매개 변수로'Object'와'Object []'를 받아 들일 방법이 필요한 이유를 설명 할 수 있습니까? 해당 코드를 사용하는 환경에 대해 더 자세히 알려주십시오. 적어도 나는 호기심이 많다. –
죄송합니다. Roland, 지금까지 언급 된 내용을 보지 못했습니다. JList의 DefaultListModel에서 객체를 꺼내서 형식을 잃어 버리면 형식이 손실되고 모델을 대체하거나 "안전하지 않은"형 변환이 옵션입니다. 나는 컴파일러가 만족스런 방식으로 캐스트를 수행 할 수 없다고 생각했지만 종종 잘못되었습니다. –