How to justify why an unchecked cast is okay, regarding Copyable getObjectCopy()

只谈情不闲聊 提交于 2019-12-02 00:07:22

问题


(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;

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

Every time you use an @SuppressWarnings("unchecked") annotation, add a comment saying why it's safe to do so.

His example is

// 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;

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

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"?


回答1:


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();
}

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!



来源:https://stackoverflow.com/questions/21421576/how-to-justify-why-an-unchecked-cast-is-okay-regarding-copyable-getobjectcopy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!