Reputation: 13379
I have an object, want to convert the generic object to class object. I thought the following should work. But it doesn't:
Object o1=itr.next();
Class cls=o1.getClass();
Object obj=(cls) o1;
What can the error be? How can I do this correctly?
Update: Here i have the list of objects that belongs to different classes. I will be using each class in each loop to convert to XML or JSON string. for this i want to get the class and object it belongs.
Upvotes: 1
Views: 938
Reputation: 42953
You have to call the cast method on the Class object:
cls.cast(o1)
Upvotes: 6
Reputation: 4180
If your iterator returns Objects that actually are of the type Class this might work:
Object o1=itr.next();
Class clazz = (Class)o1;
To be honest, your question is not really clear to me.
Upvotes: 0
Reputation: 12064
Object o1=itr.next();
Class cls=o1.getClass();
Object obj=(cls) o1; //whats does it make sense casting Object by object? o1 and obj both are object
and it can be cast by type T
, not class
Upvotes: 0
Reputation: 234857
This syntax:
Object obj=(cls) o1;
is not allowed. You can only cast to a type and cls
is an object of type Class
, not a type itself. What are you trying to accomplish with this? You could just as well write:
Object obj = o1;
since any reference type is assignment-compatible with Object
(and, besides, o1
is already of type Object
).
Upvotes: 3