如何certificate为什么未经检查的强制转换是可以的,关于Copyable getObjectCopy()
(这是我上一个问题的后续行动。)
我有一个名为Copyable
的接口,它有一个function
Copyable getObjectCopy();
这被许多其他类使用。 因为此函数始终返回Copyable
,所以会导致未经检查的强制转换。 例:
@SuppressWarnings("unchecked") //Copy of itself is the same type. ValidateValue vvo = (ValidateValue)this_toCopy.getValidator().getObjectCopy(); vvBlkA = vvo;
我的问题与Josh Bloch的建议有关(在Effective Java,第2版,第24项):
每次使用@SuppressWarnings(“未选中”)注释时,请添加注释,说明为什么这样做是安全的。
他的榜样是
// 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 vvo = (ValidateValue)this_toCopy.getValidator().getObjectCopy(); vvBlkA = vvo;
我的评论似乎很蹩脚,但我想不出更好的事情。 这就是我的问题: 为什么这种不受约束的演员合理 ? 什么是一个有意义的评论,实际上将帮助未来的开发人员,这意味着有效,“只相信我”的东西?
我们现在在Java 5+世界! 用户generics。
您可以将Copyable
的签名更改为:
interface Copyable { T getObjectCopy(); }
现在你的ValidateValue
值将是这样的:
puvlic class ValidateValue implements Copyable> { ... }
每个人(包括编译器)都会很开心!