Java,消除返回对象的方法的未检查转换

huangapple go评论81阅读模式
英文:

Java, getting rid of unchecked conversion for method returning an object

问题

我有另一个无法消除的未经检查的警告案例。代码如下:

public <FV, V> V getFieldValue(String fieldName, Function<FV, V> converter) {
  FV fieldValue = (FV) getFieldValue(fieldName); // this returns an object
  return converter.apply(fieldValue);
}

这段代码编译并运行正常,但Eclipse(和Java编译器)会警告FV类型的强制转换是不安全的。是的,它是不安全的,但我希望依赖调用者知道他们在做什么,所以我想消除警告。

Eclipse建议我在赋值或方法级别添加@SuppressWarnings("unchecked"),但都不起作用。是否有可能告诉编译器我对此不关心,不想受到干扰?

如果你认为getFieldValue() 应该使用泛型而不是Object,是的,我知道,但这是非常古老的代码,我不能改变它。

英文:

I've yet another case of unchecked warning that I cannot get rid of. Code looks like this:

public &lt;FV, V&gt; V getFieldValue ( String fieldName, Function&lt;FV, V&gt; converter )
{
  FV fieldValue = (FV) getFieldValue ( fieldName ); // this returns an object
  return converter.apply ( fieldValue )
} 

This code compiles and works fine, but Eclipse (and Java compiler) complaints that the FV casting is unsafe. Yes, it is, yet I'd like to rely on the caller knowing what they are doing, so I'd like to remove the warning.

Eclipse proposes me to add @SuppressWarnings ( &quot;unchecked&quot; ) at either the assignment or the method level, neither changes a thing. Is it possible to tell the compiler I'm fine with it and I don't want to be bothered?

If you are thinking that getFieldValue() should use a generic and not an Object, yes, I know, but it's very ancient code that I can't change.

答案1

得分: 1

只有一种确实安全的方法来处理这个问题,那就是完全删除你需要 FV 的原因:传递一个 Function&lt;Object, V&gt;(或 Function&lt;Object, ? extends V&gt;)代替。

英文:

The only actually safe way to deal with this is to remove the reason you need FV at all: pass a Function&lt;Object, V&gt; (or Function&lt;Object, ? extends V&gt;) instead.

答案2

得分: 0

这应该按预期工作 @SuppressWarnings("unchecked")。如果这不起作用,您可以尝试 @SuppressWarnings("all")

英文:

This should work as expected @SuppressWarnings(&quot;unchecked&quot;). If this doesn't work, you can try @SuppressWarnings(&quot;all&quot;)

huangapple
  • 本文由 发表于 2020年8月13日 18:36:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/63393277.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定