Avoid unchecked cast warning

Discussion in 'Java' started by Ian Pilcher, Aug 20, 2005.

  1. Ian Pilcher

    Ian Pilcher Guest

    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!

    --
    ========================================================================
    Ian Pilcher
    ========================================================================
     
    Ian Pilcher, Aug 20, 2005
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Andrew Lee
    Replies:
    2
    Views:
    3,126
    Andrew Lee
    Nov 18, 2004
  2. Knute Johnson

    Unchecked cast warning?

    Knute Johnson, Nov 1, 2006, in forum: Java
    Replies:
    4
    Views:
    1,006
    Knute Johnson
    Nov 1, 2006
  3. Knute Johnson
    Replies:
    2
    Views:
    2,068
    Knute Johnson
    Apr 15, 2007
  4. kathychow
    Replies:
    0
    Views:
    2,123
    kathychow
    Mar 31, 2009
  5. RVic
    Replies:
    19
    Views:
    1,396
Loading...

Share This Page