避免以下未经检查的警告

时间:2010-08-04 04:29:39

标签: java generics

我做了一些花哨的包装以避免过去的未经检查的警告,但是经过90分钟的p http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html之后,我无法编写下面的findMatch方法并使其在没有@SuppressWarnings的情况下工作(“未经检查“)。参数化类在编译时是未知的。

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;
  }
}

注意代码是有效的,因为在每种情况下,Matchable都是由T实现的。

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);
    }
}

1 个答案:

答案 0 :(得分:2)

public static <T extends Matchable<T>> T findMatch(T toMatch, T[] toSearch) {
  if (toMatch == null)
    return null;

  Matchable<T> matchObj = toMatch;
  Class<?> matchClass = matchObj.getClass();

  for (T obj : toSearch) {
    if (matchClass.isInstance(obj) && matchObj.matches(obj))
      return obj;
  }

  return null;
}