英文:
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 <FV, V> V getFieldValue ( String fieldName, Function<FV, V> 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 ( "unchecked" )
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<Object, V>
(或 Function<Object, ? extends V>
)代替。
英文:
The only actually safe way to deal with this is to remove the reason you need FV at all: pass a Function<Object, V>
(or Function<Object, ? extends V>
) instead.
答案2
得分: 0
这应该按预期工作 @SuppressWarnings("unchecked")
。如果这不起作用,您可以尝试 @SuppressWarnings("all")
。
英文:
This should work as expected @SuppressWarnings("unchecked")
. If this doesn't work, you can try @SuppressWarnings("all")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论