How to justify why an unchecked cast is okay, rega

2020-04-12 02:53发布

(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条回答
小情绪 Triste *
2楼-- · 2020-04-12 03:51

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!

查看更多
登录 后发表回答