9

假设我有一个名为 foo 的方法,以 2 Object 作为参数。这两个对象属于同一类型,并且都实现了可比较的接口。

void foo(Object first, Object second){

    if (!first.getClass().isInstance(second))   //first and second of the same type
        return;

    Comparable firstComparable = (Comparable)first;  //WARNING
    Comparable secondComparable = (Comparable)second;  //WARNING

    int diff = firstComparable.compareTo(secondComparable);  //WARNING
}

前 2 个警告是:

Comparable 是原始类型。对泛型 Comparable 的引用应该被参数化

最后的警告:

类型安全:方法 compareTo(Object) 属于原始类型 Comparable。对泛型 Comparable 的引用应该被参数化

我如何重构我的代码以删除这些警告?

编辑:我可以在不更改 foo 方法签名的情况下做到这一点吗?

4

5 回答 5

15

您必须告诉编译器它们是相同类型且可比较的。如果您无法更改签名,则可以添加一种向后兼容的方法。

@SuppressWarnings("unchecked")
static void foo(Object first, Object second) {
    foo((Comparable) first, (Comparable) second);
}

static <T extends Comparable<T>> void foo(T first, T second){
    int diff = first.compareTo(second); // no warning.
}
于 2011-08-10T09:48:36.227 回答
3

无需更改签名即可

    void foo(Object first, Object second){

        if (!first.getClass().isInstance(second)) 
            return;

        Comparable<Object> firstComparable = (Comparable<Object>)first;  
        Comparable<Object> secondComparable = (Comparable<Object>)second; 

        int diff = firstComparable.compareTo(secondComparable);  
    }

你仍然得到:
Type safety: Unchecked cast from Object to Comparable<Object>

但是没有Comparable is a raw type. References to generic type Comparable<T> should be parameterized
和没有Type safety: The method compareTo(Object) belongs to the raw type Comparable. References to generic type Comparable<T> should be parameterized

于 2011-08-10T09:59:38.027 回答
1

编辑:既然你说你不能改变方法的签名,那么如果没有不安全的(对编译器)强制转换,你真的无法逃脱,并且@SuppressWarnings

@SuppressWarnings("unchecked")
public void foo(final Object first, final Object second) {
    if (!first.getClass().isInstance(second)) // first and second of the
        return;

    Comparable<Object> firstComparable = (Comparable<Object>) first;
    Comparable<Object> secondComparable = (Comparable<Object>) second;
    int diff = firstComparable.compareTo(secondComparable);
}
于 2011-08-10T10:01:58.453 回答
1

您必须使用 Comparable<Type>where Type 是正在实现的对象Comparable

首先,为什么你的方法参数实例是Objects?如果您确定参数的类型相同,则应使用特定的类作为参数。如果您可以拥有类的层次结构,请在层次结构中拥有最高的类。必须Object实现一般功能绝不是一个好主意。

于 2011-08-10T09:51:04.423 回答
0

添加@SuppressWarnings 注释。

@SuppressWarnings("unchecked")
void foo(Object first, Object second){

    if (!first.getClass().isInstance(second))   //first and second of the same type
        return;

    Comparable firstComparable = (Comparable)first;  //WARNING
    Comparable secondComparable = (Comparable)second;  //WARNING

    @SuppressWarnings("unused")
    int diff = firstComparable.compareTo(secondComparable);  //WARNING
}
于 2011-08-10T09:45:23.640 回答