2
我已经做了一些奇特的包装,以避免过去未经检查的警告,但90分钟后深入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;
}
}
注意代码的工作,因为在任何情况下可匹配由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);
}
}
这是正确的,我应该在问题上已经更清楚了。我需要一个使用非参数化类型的方法签名(当他们遇到有问题的代码时,他们已经丢失了)。 现在,如果有一种方法可以将通用对象转换为可供此方法使用的方式,我很乐意学习它。下面是不行的,但是这是基本的想法... ' 公共静态>对象findMatch(对象toMatch,对象[] toSearch) { 回报findMatch((T)toMatch ,(T [])toSearch); } ' –
2010-08-04 13:32:41
你能解释为什么你需要你的方法接受'Object'和'Object []'作为参数而不是'Matchable'和'Matchable []'吗?告诉我们更多关于您使用该代码的环境。至少我很好奇。 – 2010-08-04 19:25:35
对不起罗兰,我现在没有看到评论。 我把对象从JList的DefaultListModel中拉出来,所以类型在放入之后会丢失,并且替换模型或“不安全”的投射是选项。我以为编剧不能以编辑满意的方式完成,但我常常是错的。 – 2010-08-08 15:18:37