(这是对我的previous question的跟进。)
我有一个名为Copyable
的接口,它只有一个函数
Copyable getObjectCopy();
这是许多其他类使用的。因为这个函数总是返回一个Copyable
,所以它会导致未检查的强制转换。示例:
@SuppressWarnings("unchecked") //Copy of itself is the same type.
ValidateValue<L> vvo = (ValidateValue<O>)this_toCopy.getValidator().getObjectCopy();
vvBlkA = vvo;
我的问题涉及乔希·布洛奇的建议(“有效Java”,第二版,第24项):
每次使用@SuppressWarnings("unchecked")注释时,都会添加一个注释,说明为什么这样做是安全的。
他的榜样是
// 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页底部:Ch05.pdf)
我喜欢这个主意,我想用getObjectCopy()
@SuppressWarnings("unchecked") //Copy of itself is the same type.
ValidateValue<L> vvo = (ValidateValue<O>)this_toCopy.getValidator().getObjectCopy();
vvBlkA = vvo;
我的评论似乎很蹩脚,但我想不出比这更好的了。这就是我的问题:为什么这个未经检查的广播是合理的?什么是有意义的评论,实际上将帮助未来的开发人员,这意味着,实际上,不仅仅是“相信我”?
发布于 2014-01-29 05:18:34
我们现在在爪哇5+世界!用户概论。
可以将Copyable
的签名更改为如下所示:
interface Copyable<T extends Copyable> {
T getObjectCopy();
}
现在,您的ValidateValue<L>
值应该是如下所示:
puvlic class ValidateValue<L> implements Copyable<ValidateValue<L>> {
...
}
每个人(包括编译器)都会很高兴!
https://stackoverflow.com/questions/21421576
复制相似问题