如何证明为什么未经检查的强制转换是可以的,关于Copyable getObjectCopy() [英] How to justify why an unchecked cast is okay, regarding Copyable getObjectCopy()

查看:134
本文介绍了如何证明为什么未经检查的强制转换是可以的,关于Copyable getObjectCopy()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(这是对我的上一个问题的跟进。)

(This is a follow-up to my previous question.)

我有一个名为可复制的接口,它有一个功能

I have an interface called Copyable, which has a single function

Copyable getObjectCopy();

许多其他类使用它。因为此函数始终返回可复制,所以会导致未经检查的强制转换。示例:

This is used by many other classes. Because this function always returns a Copyable, it results in unchecked casts. Example:

@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项) :

My question relates to Josh Bloch`s recommendation (in Effective Java, 2nd ed., item 24):


每次使用@SuppressWarnings(未选中)注释时,请添加注释,说明为什么这样做是安全的。

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

(see the bottom of page 9 / 117: http://www.infoq.com/resource/articles/bloch-effective-java-2e/en/resources/Bloch_Ch05.pdf)

我喜欢这个想法,我希望用 getObjectCopy()

I like this idea, and I want to it with getObjectCopy()

@SuppressWarnings("unchecked")  //Copy of itself is the same type.
ValidateValue<L> vvo = (ValidateValue<O>)this_toCopy.getValidator().getObjectCopy();
vvBlkA = vvo;

我的评论似乎很蹩脚,但我想不出更好的事情。这就是我的问题:为什么这个未经检验的演员合理?什么是一个有意义的评论,实际上将帮助未来的开发人员,这意味着有效的,只相信我?

My comment seems lame, but I can't think of anything better. And that's my question: Why is this unchecked-cast justifiable? What's a meaningful comment that would actually help future developers, that means something more than, effectively, "just trust me"?

推荐答案

我们现在在Java 5+世界!用户泛型。

We are in Java 5+ world now! User Generics.

您可以将可复制的签名更改为:

You can change the signature of Copyable to something like:

interface Copyable<T extends Copyable> {
    T getObjectCopy();
}

现在你的 ValidateValue< L> value将类似于:

Now your ValidateValue<L> value would be something like:

puvlic class ValidateValue<L> implements Copyable<ValidateValue<L>> {
    ...
}

并且每个人(包括编译器)都会快乐!

and everyone (including the compiler) would be happy!

这篇关于如何证明为什么未经检查的强制转换是可以的,关于Copyable getObjectCopy()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆