• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Class cast problem

 
smitha rai
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I have a public method which takes String as a parameter which actually represents a class name. My requiremnet is to cast the value i get from a collection object to the class name represented by the string parameter. For example
public String getValueObject(String className) {
java.util.ArrayList al = getData();
for(int i=0; i < al.size(); i++) {
className cn = (className) al.get(i);
//At this instance i am getting error
}
return null;
}
Appreciate if some could help me in correcting the code.
Regards.
Smitha
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 65123
91
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No amount of machinations in your code is going to allow you to cast the element from the collection to a class that it is not really an instance of.
For example, if your collection is full of instances of java.util.Date, you can't cast them to a java.lang.String.
The instances in the collection must either be direct instances of, subclasses of, or implementors of the class or interface that you are trying to cast it to.
So the questions are: what are the classes in your collection? what are you trying to cast them to?
The method Class.isAssignableFrom() might be helpful to you.
hth,
bear
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
smitha,
We ain't got many rules 'round these parts, but we do got one. Please change your display name to comply with The JavaRanch Naming Policy.
Thanks Pardner!
 
Cindy Glass
"The Hood"
Sheriff
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dirk - you have acquired a western accent .
Geez - don't forget about that rule "Be friendly". Paul gets REAL stern about that .
That's TWO rules now .
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic