File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Casting, objects, and wrappers Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "Casting, objects, and wrappers" Watch "Casting, objects, and wrappers" New topic
Author

Casting, objects, and wrappers

Charles McGuire
Ranch Hand

Joined: Jan 18, 2005
Posts: 99
I have an object. If I know it is an Integer, can I cast the object to Integer in order to execute a method on it?



This is giving me the error: the method intValue() is undefined for the type object. Yet, I thought the cast to (Integer) would do that. I have what must be an inefficient work around. Yuck.



Yuck. If I know obj is of type Integer (from the instanceof test), how do I execute methods of Integer on that object??


There's no place like 127.0.0.1
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24043
    
  13

You just need some more parentheses. "(Integer) obj.intValue()" means to call intValue() on obj, and cast the result to Integer. On the other hand, "((Integer) obj).intValue()" means to cast obj to Integer, and call intValue() on that Integer.


[Jess in Action][AskingGoodQuestions]
Charles McGuire
Ranch Hand

Joined: Jan 18, 2005
Posts: 99
Thank you!!!

I feel like an idiot. Thrice an idiot:

Once for not knowing this.
Again for not finding this in my hard copy reference books.
Again for not being able to construct a forum search string to find this (I looked).
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Casting, objects, and wrappers
 
Similar Threads
from int to Integer casting?
TypeFactory can it be done in java?
Integer class
Var args ... explanation needed
Objects equal method