• Post Reply Bookmark Topic Watch Topic
  • New Topic

Generic Object as a parameter to a method  RSS feed

 
Salmon Chase
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.
 
marc weber
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 ]
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!