(这是我的 previous question 的后续。)
我有一个名为Copyable
的接口(interface),它只有一个函数
Copyable getObjectCopy();
这被许多其他类使用。因为此函数总是返回一个 Copyable
,所以它会导致未经检查的强制转换。示例:
@SuppressWarnings("unchecked") //Copy of itself is the same type.
ValidateValue<L> vvo = (ValidateValue<O>)this_toCopy.getValidator().getObjectCopy();
vvBlkA = vvo;
我的问题与 Josh Bloch 的建议(Effective Java,第 2 版,第 24 项)有关:
Every time you use an @SuppressWarnings("unchecked") annotation, add a comment saying why it's safe to do so.
他的例子是
// 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());
return result;
(见第 9/117 页底部:http://www.infoq.com/resource/articles/bloch-effective-java-2e/en/resources/Bloch_Ch05.pdf)
我喜欢这个想法,我想用 getObjectCopy()
@SuppressWarnings("unchecked") //Copy of itself is the same type.
ValidateValue<L> vvo = (ValidateValue<O>)this_toCopy.getValidator().getObjectCopy();
vvBlkA = vvo;
我的评论似乎很蹩脚,但我想不出更好的。这就是我的问题:为什么这种未经检查的转换是合理的?什么是真正对 future 的开发者有帮助的有意义的评论,而不仅仅是“相信我”?
最佳答案
我们现在处于 Java 5+ 世界!用户泛型。
您可以更改 Copyable
的签名类似于:
interface Copyable<T extends Copyable> {
T getObjectCopy();
}
现在您的 ValidateValue<L>
值(value)将是这样的:
puvlic class ValidateValue<L> implements Copyable<ValidateValue<L>> {
...
}
每个人(包括编译器)都会很高兴!
关于java - 关于 Copyable getObjectCopy(),如何证明为什么未经检查的类型转换没问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21421576/