This week's book giveaway is in the Agile and Other Processes forum.
We're giving away four copies of The Journey To Enterprise Agility and have Daryl Kulak & Hong Li on-line!
See this thread for details.
Win a copy of The Journey To Enterprise Agility this week in the Agile and Other Processes forum! And see the welcome thread for 20% off.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Junilu Lacar
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Ganesh Patekar
  • Tim Moores
  • Pete Letkeman
  • Stephan van Hulst
Bartenders:
  • Carey Brown
  • Tim Holloway
  • Joe Ess

Generic Object as a parameter to a method  RSS feed

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a method that takes Object o as an input parameter. I am wondering if this logic is going to work if I pass it a Report object:

if (o.getClass().getName().equals("Report")) {

Report report = new Report();

report = o; //This probably doesn't work.

}

Will the conditional statement work and how do I assign the values in o to report?

Thanks.
 
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Originally posted by Salmon Chase:
...if (o.getClass().getName().equals("Report")) {...
Will the conditional statement work...


Yes, and you can add some println statements to your code to demonstrate this. But it might be easier (and more efficient!) to use the instanceof operator...

if(o instanceof Report) {...

Originally posted by Salmon Chase:
...Report report = new Report();
report = o; //This probably doesn't work...


No, it doesn't, and the error message tells you why.

...incompatible types
found : java.lang.Object
required: Report...

Since you're downcasting (from Object to Report), you need an explicit cast. Indeed, this is why the conditional test is a good idea -- to verify what you have before attempting a cast that might otherwise cause a RuntimeException.

Also, it doesn't make much sense to create a new object only to reassign the variable in the next line. This just creates a new instance that's immediately ready for Garbage Collection.
[ August 10, 2006: Message edited by: marc weber ]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!