[Effective Java] Item 24:Eliminate unchecked warnings

什么是 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;
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值