• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Generic Object as a parameter to a method

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
Seriously Rick? Seriously? You might as well just read this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic