• Post Reply Bookmark Topic Watch Topic
  • New Topic

Casting, objects, and wrappers  RSS feed

 
Charles McGuire
Ranch Hand
Posts: 99
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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??
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Charles McGuire
Ranch Hand
Posts: 99
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!