Cast from Object to int?

G

gaztedo

Hi there!

I'm developing a method which receives two Object parameters, and I need
to cast one of them to int. How can I do it?

public method(Object a, Object b){
this.b = (int)b; // doesn't work!
this.a = a;
}

Thanks in advance!
 
T

Thomas Kellerer

gaztedo, 20.12.2007 12:43:
Hi there!

I'm developing a method which receives two Object parameters, and I need
to cast one of them to int. How can I do it?

public method(Object a, Object b){
this.b = (int)b; // doesn't work!
this.a = a;
}

I guess the fact that your method declaration is invalid syntax is a
typing error in the email.

You cannot cast an Object to an int. If b is e.g. a Number object (e.g.
Integer or Long) you can do the following:

this.b = ((Number)b).intValue()

Btw: why don't you simple define your method as
public void method(Object o, int value)

Thomas
 
G

gaztedo

You cannot cast an Object to an int. If b is e.g. a Number object (e.g.
Integer or Long) you can do the following:

this.b = ((Number)b).intValue()

Thanks! It worked nice!
Btw: why don't you simple define your method as
public void method(Object o, int value)

I cannot do it... it's a long story ;)
 
R

Roedy Green

I'm developing a method which receives two Object parameters, and I need
to cast one of them to int. How can I do it?
You can't because int is not an Object. You could cast it perhaps to
Integer or to whatever the object actually was. From there you can
convert, but not cast, it to int.

See http://mindprod.com/jgloss/conversion.html

To find out what kind of animal you have:

System.out.println( obj.getClass().toString() );
 
G

gaztedo

Fortunately this is a big discussion forum, and
a lot of people enjoy a long story.

Well, not such a huge story. I'm developing a parser using Yacc, and it
requires to develop some constructors (before I said methods, sorry)
using Object as a type.

So that was the reason I had to use Object and I couldn't use Integer.

BTW I still have a lot of different errors :S
 

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,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top