javafindbugs

Unchecked casting complain by FindBugs


Consider the following code :

 public void broadcast(FacesEvent event)
    throws AbortProcessingException {

    if(!(event instanceof WrapperEvent)) {
      super.broadcast(event);
      return;
    }

    // Sets up the correct context and fire our wrapped event.
    GridWrapperEvent revent = (GridWrapperEvent)event; // FindBugs is complaining here 
    int oldRowIndex = getRowIndex();
    int oldColumnIndex = getColumnIndex();
    boolean oldClientIdRewritting = clientIdRewritting;
    setClientIdRewritting(revent.isClientIdRewritting());

    setActiveCell(revent.getRowIndex(), revent.getColumnIndex());

    FacesEvent rowEvent = revent.getFacesEvent();
    rowEvent.getComponent().broadcast(rowEvent);
    setActiveCell(oldRowIndex, oldColumnIndex);
    setClientIdRewritting(oldClientIdRewritting);
  }

FindBugs is complaining about the commented line. Is there anything that I can do about it? This is what FindBugs says:

Unchecked/unconfirmed cast This cast is unchecked, and not all instances of the type casted from can be cast to the type it is being cast to. Ensure that your program logic ensures that this cast will not fail.


Solution

  • If you know that event will always be a GridWrapperEvent, you can ignore the warning. Otherwise you can wrap the cast (and the logic depending on it) inside a check like

    if (event instanceof GridWrapperEvent) {
      // ...
    }
    

    In fact you're already doing this, but for the (I assume) more generic WrapperEvent class. Perhaps you could adapt that check instead of adding a new one.