avoiding ClassCastException

M

Madhur Ahuja

Hello

I currently make use of a program which employs both *AWT Buttons* and
*swing JButtons*.
In the *actionPerformed(ActionEvent e)* function of my program
how do I handle events coming from both types of buttons.
Currently I am doing this :

public void actionPerformed(ActionEvent e)
{

JButton obj=null;
Button obj1=null;
try
{
obj=(JButton)e.getSource();
}

catch(Exception ClassCastException)
{
}


try
{
obj1=(Button)e.getSource();
}

catch(Exception ClassCastException)
{
}

if(obj==start) /*start is of type Button*/
{

}
if(obj1==reset) /*reset is of type JButton*/
{

}

This generates ClassCastException everytime I click a button.
But I am sure there must be a way
to avoid this.

--
Winners dont do different things, they do things differently.

Madhur Ahuja
India

Homepage : http://madhur.netfirms.com
Email : madhur<underscore>ahuja<at>yahoo<dot>com
 
A

Andrew Thompson

I currently make use of a program which employs both *AWT Buttons* and
*swing JButtons*.

Why? There are *very* few situations
in which you should ne doing that.
In the *actionPerformed(ActionEvent e)* function of my program
how do I handle events coming from both types of buttons.
Currently I am doing this :

public void actionPerformed(ActionEvent e)
{

Object object = (Object)e.getSource();
if (object==start) /* start is of type Object */ {
.....
}
else if (object==reset) /* reset is of type Object */ {
.....
}
}
This generates ClassCastException everytime I click a button.
But I am sure there must be a way
to avoid this.

Have you considered posting to a group
better suited to beginners?
<http://www.physci.org/codes/javafaq.jsp#cljh>
 
M

Matt Humphrey

Madhur Ahuja said:
Hello

I currently make use of a program which employs both *AWT Buttons* and
*swing JButtons*.
In the *actionPerformed(ActionEvent e)* function of my program
how do I handle events coming from both types of buttons.
Currently I am doing this :

I don't recommend mixing AWT and Swing buttons. I also usually provide a
unique listener for each button so that there's no lookup problem and let
the listener invoke the appropriate action method. However, to answer your
question, you can avoid the ClassCastException in the following way: Rather
than casting e.getSource () to JButton, cast obj / obj1 to (Object).

if (e.getSource () == (Object)start) {
// It's the start button
} else if (e.getSource () == (Object)reset) {
// It's the reset button
}

Other alternatives are

1) Provide a specific listener for each button using anonymous classes
myButton.addActionListener (new ActionListener () {
public void actionPerformed (ActionEvent e) {
doMyButtonAction ();
}
}
);

2) Use one listener for JButton and another for Button

3) Put your buttons in a Map
actionMap.put (button (or jbutton), Action)
Action a = (Action)actionMap.get (button or Jbutton)

4) Test the e.getSource () type directly via instanceof, as in
if (e.getSource () instanceof JButton) {
} else if (e.getSource () instanceof Button) {
} etc.


Cheers,

Matt Humphrey (e-mail address removed) http://www.iviz.com/
 
K

kjc

Number one, DON"T mix swing components and AWT components. It's BAD
design. But,if you want to do conditional logic based on the class
DO NOT use instance of. The most reliable way to test for class
is to:
if (e.getSource().getClass() == JButton.class) {
} else if (e.getSource().getClass() == Button.class) {
} etc.
 
C

Christophe Vanfleteren

kjc said:
Number one, DON"T mix swing components and AWT components. It's BAD
design. But,if you want to do conditional logic based on the class
DO NOT use instance of. The most reliable way to test for class
is to:
if (e.getSource().getClass() == JButton.class) {
} else if (e.getSource().getClass() == Button.class) {
} etc.

Care to explain why you wouldn't use instanceof ? It is *very* rare to need
to know the *exact* class of an object, most of the time it suffices to
know if it can "act" as one.

In your case, code like that would break the minute you're using a JButton
subclass, while the instanceof method would continue to work.
 
B

Brian Palmer

Matt Humphrey said:
I don't recommend mixing AWT and Swing buttons. I also usually provide a
unique listener for each button so that there's no lookup problem and let
the listener invoke the appropriate action method. However, to answer your
question, you can avoid the ClassCastException in the following way: Rather
than casting e.getSource () to JButton, cast obj / obj1 to (Object).

if (e.getSource () == (Object)start) {
// It's the start button
} else if (e.getSource () == (Object)reset) {
// It's the reset button
}

There's no reason to cast start and reset to Object. Java doesn't let
you override operator==, so objects are always compared by identity.

if (e.getSource() == start) {

} else if (e.getSource() == reset) {

}
 
M

Matt Humphrey

Brian Palmer said:
There's no reason to cast start and reset to Object. Java doesn't let
you override operator==, so objects are always compared by identity.

if (e.getSource() == start) {

} else if (e.getSource() == reset) {

}

Quite right--thanks for pointing that out.

Cheers,
Matt Humphrey (e-mail address removed) http://www.iviz.com/
 
C

Chad M

"Madhur Ahuja" <[email protected]> said:
public void actionPerformed(ActionEvent e)
{
JButton obj=null;
Button obj1=null;
try
{
obj=(JButton)e.getSource();
}
catch(Exception ClassCastException)
{
}
try
{
obj1=(Button)e.getSource();
}
catch(Exception ClassCastException)
{
}

if(obj==start) /*start is of type Button*/
{

}
if(obj1==reset) /*reset is of type JButton*/
{

}

Leaving aside the issues of whether you should be mixing AWT and swing
buttons, and whether they should use the same ActionListener, why are
you casting at all? Equality does not care about static type, so you can
just jump to the line where you test if the source is "start" or
"reset". I.e. it seems like you think the following test:

JButton j = new JButton();
Object o = j;
if(o==j) ...

either will return false, or will require a cast. It works as written
and the test "o==j" returns true. So in your code, just test directly if
e.getSource() == start or == reset.

-Chad
 
T

Thomas G. Marshall

Christophe Vanfleteren said:
Care to explain why you wouldn't use instanceof ? It is *very* rare
to need to know the *exact* class of an object, most of the time it
suffices to know if it can "act" as one.

I would like to know what he's talking about too. /instanceof/ is perfect
for such things.

In your case, code like that would break the minute you're using a
JButton subclass, while the instanceof method would continue to work.

BINGO.
 
K

kjc

This is a ridiculous discussion, since, if you have to rely on
instanceof to make your development correct. You should not be
developing. As far as needing to know the exact class being a "rare
case", the person that made this statement obviously is clueless about
security and server side development. If you're looking for an
explaination regarding the previous sentence. You will not get one.
Try doing some research.
 
C

Christophe Vanfleteren

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.

That sure is a very broad statement. There are many programming models that
require you to use instanceof instead of getClass().

What if you program against interfaces? What class should I be comparing
with then? What about dynamic proxies? And just about any other case where
the exact class is not known at development time.
As far as needing to know the exact class being a "rare
case", the person that made this statement obviously is clueless about
security and server side development. If you're looking for an
explaination regarding the previous sentence. You will not get one.
Try doing some research.

Oh please, stop with all the "I'm smarter than you and if you don't do what
I say, you're obviously an idiot" handwaving and give us a *real*,
explained reason why you shouldn't use instanceof in this case.

I've done the google search, and I can't seem to find an article that
clearly explains the cases in which using instanceof is a security risk.
Care to give some of your resources?

One of the times you might not want to use instanceof is in an equals
method, since you might end up with a non symmetric equals.
 
M

Madhur Ahuja

Chad M said:
Leaving aside the issues of whether you should be mixing AWT and swing
buttons, and whether they should use the same ActionListener, why are
you casting at all? Equality does not care about static type, so you can
just jump to the line where you test if the source is "start" or
"reset". I.e. it seems like you think the following test:

JButton j = new JButton();
Object o = j;
if(o==j) ...

either will return false, or will require a cast. It works as written
and the test "o==j" returns true. So in your code, just test directly if
e.getSource() == start or == reset.

-Chad

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;

produces:

E:\programs\java1\game.java:240: inconvertible types
found : java.awt.event.ActionEvent
required: javax.swing.JButton
JButton obj=(JButton)e;

--
Winners dont do different things, they do things differently.

Madhur Ahuja
India

Homepage : http://madhur.netfirms.com
Email : madhur<underscore>ahuja<at>yahoo<dot>com
 
M

Madhur Ahuja

Thanks, it worked.
But in API Documentation, I couldn't find any member named *class* in
JButton or Button.
Is it something universal or I am missing something.

--
Winners dont do different things, they do things differently.

Madhur Ahuja
India

Homepage : http://madhur.netfirms.com
Email : madhur<underscore>ahuja<at>yahoo<dot>com
 
K

kjc

getClass() is a method defined in object.

Madhur said:
Thanks, it worked.
But in API Documentation, I couldn't find any member named *class* in
JButton or Button.
Is it something universal or I am missing something.

--
Winners dont do different things, they do things differently.

Madhur Ahuja
India

Homepage : http://madhur.netfirms.com
Email : madhur<underscore>ahuja<at>yahoo<dot>com
 
T

Thomas G. Marshall

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]...
 
T

Thomas G. Marshall

kjc said:
getClass() is a method defined in object.


Try to pay attention. He said "class" not "getClass".

Madhur, "class" is defined in the java language spec, and is part of
something called a "Class Literal".

Basically, "HooHaa.class" yields an instance of java.lang.Class representing
the class HooHaa.

http://java.sun.com/docs/books/jls/second_edition/html/expressions.doc.html#251530
<quote>
15.8.2 Class Literals
A class literal is an expression consisting of the name of a class,
interface, array, or primitive type followed by a `.' and the token class.
The type of a class literal is Class. It evaluates to the Class object for
the named type (or for void) as defined by the defining class loader of the
class of the current instance.
</quote>
 
K

kjc

Ever heard of security,genious.
And, if you're clueless about the reference to security in the context
of checking for the exact class, then. As I stated before, this
discussion is a waste of good oxygen.
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]...
 
B

Brian Palmer

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.

How do you plan on doing double dispatch, then?
 
T

Tor Iver Wilhelmsen

kjc said:
And, if you're clueless about the reference to security in the context
of checking for the exact class, then. As I stated before, this
discussion is a waste of good oxygen.

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

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

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,818
Latest member
Brigette36

Latest Threads

Top