java压制警告,解决“未经检查的警告”在Java中避免@supressWarning

This is a Trying to improve my code question. About generics and the unchecked warning; I do know about the @suppresswarning annotation. The question is what am I suppose to code to suppress it. Take, please, the following code.

public class NumericBox implements Box {

private T element;

public NumericBox(T element) {

this.element = element;

}

@Override public T getElement() {

return element;

}

public T insert(Number newElement) {

T oldElement = this.element;

this.element = (T) newElement; // warning("unchecked")

return oldElement;

}

}

What is the coding way to do this (not the annotation). In the docs I've found

The term "unchecked" means that the compiler does not have enough type information to perform all type checks necessary to ensure type safety. But, don't get it. This seems ok for me:

void foo(Number n) {

Short asShort = (Short) n; //OK

T asTypeWhichExtendsNumber = (T) n; // warning

}

Extra. if I want to add an empty constructor, is any way to keep a "ZERO" in element?

NumeircBox o = new NumericBox<>(); // expectes 0 in the element

解决方案

Lets look at the code in question, your class declaration:

public class NumericBox implements Box

So we have some type T that extends Number. This might be Long, Integer etc. But some specific and defined at compile time type.

Now you have a method:

public T insert(Number newElement) {

T oldElement = this.element;

this.element = (T) newElement;

return oldElement;

}

Which takes some Number of any type - neither specfic nor defined at compile time and you coerce it into a T. This is a ClassCastException waiting to happen.

final NumericBox box = new NumericBox<>();

box.insert(3);

final BigDecimal val = box.getElement();

There is no way to avoid this warning because the compiler is telling you example this, you have an unchecked cast that could, at runtime, cause a ClassCastException. The compiler is washing its hands of that line.

So, to solve your problem, change the code to:

public T insert(T newElement) {

T oldElement = this.element;

this.element = (T) newElement;

return oldElement;

}

As generics are erased at compile time, there is not really any way of fixing that hack. If you want to guarantee runtime type safety you need to change the signature. If you want to take "any old Number" then you will have to deal with the consequences.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值