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!
First of all, casting just means "lets treat this as if it were type x".
Why can't you require a parameter of type Integer or even int?
--
Sabine Dinis Blochberger
Op3racional
www.op3racional.eu
Please don't multipost. Read the FAQ, it was just posted by David Alex
Lamb.
Sabine Dinis Blochberger wrote:
> Please don't multipost. Read the FAQ, it was just posted by David Alex
> Lamb.
In the first place, gaztedo, 'int' is not an object type, so no Object can
ever be cast to 'int'. In the second place, there's no way to guarantee to a
public method that its argument values are of any particular subtype or value,
or conversely, that they aren't. These conditions therefore have to be
checked inside the method. Third, Sabine has given you a good idea about
letting the method signature determine the type as narrowly as you need.
Finally, although you named your code snippet 'method', you gave it the syntax
of 'constructor'. You must provide a return type for a method, e.g.,
public void foo( int a, int b ) { ... }
--
Lew
Refer to the advice others have given about good OO practices, etc (i.e.
what you are trying to do here probably is NOT the best way to go about
things). Having said that, you might try the following. If you are on Java
1.5 or higher, you can take advantage of auto-boxing/unboxing.
public void method(Object a, Object b)
{
if (b instanceof Integer)
{
this.b = (Integer)b; // Cast to Integer, not int. Will auto-unbox the
Integer as an int and store to this.b.
}
this.a = a;
}
Cheers,
-Matt
public static void method(Object a, Object b) {
int bb = (Integer)b;
int aa = (Integer)a;
}
"gaztedo" <du...@mail.com> wrote in message
news:476a558a$1...@filemon1.isp.telecable.es...
> public static void method(Object a, Object b) {
> int bb = (Integer)b;
> int aa = (Integer)a;
In JDK 1.5+ which has autounboxing.
In older Java you need to unbox manually.
int bb = ((Integer)b).intValue();
--
Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com