什么是 unchecked warning
Unchecked warning是由于compiler没有足够的type信息,无法判断某个操作是否type safety,所以给了warning。比如把一个raw type返回值的方法赋值给了一个generic type,compiler无法知道raw type集合里面的实例时什么,所以就不能肯定这个赋值的正确性,所以给与了警告,很有可能在runtime就发生了ClassCastException.
所以每一个unchecked warning都表示可能在runtime时会throw ClassCastException.所以你要尽可能的消除这些warning。如果不能消除,但是你能确保引起warning的这段代码是safe的,你可以用@SuppressWarnings(“unchecked”)注释掉并且加上你的comment解释下为什么这么做是safe的,并且要保证是尽在这一小段代码范围内注释掉,不要轻易将注释放在method这一层,或甚至放在class这一层,这样会把整个class的unchecked warning都被掩盖掉。
举个例子: ArrayList toArray() method
// Unchecked cast
public <T> T[] toArray(T[] a){
if(a.length < size)
return (T[]) Arrays.copyOf(elements, size, a.getClass());// unchecked cast Object[] to T[]
System.arraycopy(elements, 0, a, 0, size);
if(a.length > size)
a[size] == null;
return a;
}
}
由于你不能再return statement上面加suppress annotation,因为它不是declaration。虽然你可以suppress在method level,但是建议你声明一个local variable to hold this return value,and annotate its declaration
// Adding local variable to reduce scope of @SuppressWarnings
public <T> T[] toArray(T[] a){
if(a.length < size){
// This cast is correct because the array we're creating
// is of the same type as the one passed in, which is T[].
@SuppressWarnings("unchecked")
T[] result = (T[]) Arrays.copyOf(elements, size, a.getClass())T[]
return result;
}
System.arraycopy(elements, 0, a, 0, size);
if(a.length > size)
a[size] == null;
return a;
}
}