avoiding ClassCastException

C

Chad M

"Madhur Ahuja" <[email protected]> said:
What if I want to perform additional operations on e, for example a
different operation if it is
a button, something different if it is a JButton.
For Example
This is what I am doing:

if(obj.getSource()==x[j]&&obj.getIcon()==null)

Here , I cant replace obj with e, since e doesnt have getIcon.

Doing :

JButton obj=(JButton)e;


But e was the ActionEvent, so of course this won't work. Once you have
determined that e.getSource() is a JButton, you can then cast the result
of getSource() to JButton--you can't cast e itself.

However, in your case you are testing with equality for a reference that
you already have. So if "myJButton" is your existing reference, just do

if(e.getSource()==myButton)
{
// do stuff with myButton, which is already of type JButton.
// no cast needed.
}

However, at this point you really should look at the idea of using
distinct ActionListeners for distinct actions. It makes a lot of the
hoops you are trying to jump through unnecessary.

-Chad
 
T

Thomas G. Marshall

Tor Iver Wilhelmsen said:
Unless you can come up with references to why instanceof is a security
problem, we can only conclude you're making things up here.

Yep. He's cornered with a mistake, and instead of admitting it he has
decided to further deepen the hole he's in.
 
T

Thomas G. Marshall

kjc said:
Thomas said:
kjc said:
This is a ridiculous discussion, since, if you have to rely on
instanceof to make your development correct. You should not be
developing.


Huh? RTTI has a place. It's easy to abuse, but many times for
pragmatic reasons it becomes critical.

And it was /YOU/ who suggested the worst idea of all: Checking the
precise name of the class.

...[rip]...
Ever heard of security,genious.

Might want to spell genius correctly, genius.

You're making a huge fool of yourself, you should realize it by now. For
your own sake, consider growing up, or at the very least, stopping.

....[rip]...
 

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,995
Messages
2,570,230
Members
46,819
Latest member
masterdaster

Latest Threads

Top