javasyntax

Can I cast and work with an Object on one line?


Normally, I do something like this:

public showDialog(final Object caller) {
    JDialog dialog = [ ... ]

    if (caller instanceof Window) {
        Window w = (Window) caller;
        dialog.setLocationRelativeTo(w);
        w.dispose();
    }
}

However, is there a one-line way to do it? Basically, something like: (Window) parent.dispose(); Or do I always need to create a Window to store my cast?


Solution

  • Yes:

    dialog.setLocationRelativeTo((Window) caller);
    

    If you want to call a method on the casted value, you'll have to enclose it into a set of parenthesis:

    ((Window) caller).dispose();
    

    Personally I'd only do that if that's the only thing I do with it. If there are two or more statements where I needed the value with the cast, then I'd use an explicit variable as you've done in your original code.