为什么这种通用方法不安全? [英] Why is this generic method unsafe?
问题描述
以下方法会产生警告,但对我来说看起来很安全。我确信问题出在我身上:
public< S扩展了CharSequence> S foo(S s){
return(S)new StringBuilder(s);
}
它看起来像总是返回参数 s
。任何人都可以显示一个会导致此方法抛出异常的例子吗?
编辑:我对于是否特别感兴趣泛型在这里是必要的。相反,我正在寻找这种方法如何不安全的演示。
foo(test); p>
足以让java尝试在String中投射一个StringBuilder。
你的代码保证是错误的,你能解释一下你想要达到的目标吗?
The following method generates a warning, but it looks safe to me. I'm sure the problem is with me:
public <S extends CharSequence> S foo(S s) {
return (S) new StringBuilder(s);
}
It looks like this will always return the argument s
. Can anyone show an example that would cause this method to throw an exception?
Edit: I'm not particularly interested in the question of whether generics are necessary here. Rather, I'm looking for a demonstration of how this method is unsafe.
foo("test");
is enough to make java try to cast a StringBuilder in a String.
Your code is guaranteed o be wrong, can you explain what you're trying to achieve plase ?
这篇关于为什么这种通用方法不安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!