代码之家  ›  专栏  ›  技术社区  ›  Steve Jackson

避免以下未检查的警告

  •  2
  • Steve Jackson  · 技术社区  · 14 年前

    http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html ,我无法在没有@SuppressWarnings(“unchecked”)的情况下编写下面的findMatch方法并使其工作。参数化类在编译时未知。

    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 回复  |  直到 14 年前
        1
  •  2
  •   Roland Illig    14 年前
    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;
    }