File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Class cast problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Class cast problem" Watch "Class cast problem" New topic

Class cast problem

smitha rai
Ranch Hand

Joined: Aug 15, 2001
Posts: 33
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.
Bear Bibeault
Author and ninkuma

Joined: Jan 10, 2002
Posts: 63852

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.

[Asking smart questions] [About Bear] [Books by Bear]
Dirk Schreckmann

Joined: Dec 10, 2001
Posts: 7023
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!

[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
Cindy Glass
"The Hood"

Joined: Sep 29, 2000
Posts: 8521
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 .

"JavaRanch, where the deer and the Certified play" - David O'Meara
I agree. Here's the link:
subject: Class cast problem
It's not a secret anymore!