Avoid unchecked cast warning

I

Ian Pilcher

I have a generic class, Value<T>, that is most often instantiated
dynamically, based on the contents a data file. From the compiler's
point of view, this leaves my with an oh-so-useful Value<?>.

I am trying to write a method to "narrow" the type of reference to one
of these objects, similar to Class.asSubclass(Class):

public <U> Value<? extends U>narrowTo(Class<U> cls)
{
// Check for compatibility here

return (Value<? extends U>)this;
}

From what I can tell, this works, but it gives me an unchecked cast
warning (or an "unchecked or unsafe operation" warning). There doesn't
seem to be any way to tell the compiler that I know what I'm doing.

This is extremely annoying for those of us who think that compiler
warnings generally indicate something that needs to be addressed. It
also strikes me as a bit overzealous on the part of Sun's compiler team.

After all, the compiler doesn't spit out a warning for traditional
casts, and it can't check those either. In fact, that is the whole
point of a cast. It is the developer's way of telling the compiler that
he or she has information that the compiler doesn't. The whole idea of
an "unchecked cast" warning is backwards; if the compiler had enough
information to check the cast, the cast wouldn't be necessary in the
first place!

Thoughts?

Thanks!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,144
Latest member
KetoBaseReviews
Top