This week's book giveaway is in the Java 8 forum.
We're giving away four copies of Java 8 in Action and have Raoul-Gabriel Urma, Mario Fusco, and Alan Mycroft on-line!
See this thread for details.
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


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Class cast problem" Watch "Class cast problem" New topic
Author

Class cast problem

smitha rai
Ranch Hand

Joined: Aug 15, 2001
Posts: 33
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

Joined: Jan 10, 2002
Posts: 60077
    
  65

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


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Dirk Schreckmann
Sheriff

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


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

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: http://aspose.com/file-tools
 
subject: Class cast problem
 
Similar Threads
Parameter and Argument !
Cast Exceptions on result of a JSR-233 (java) call.
JAR file
Dynamic creation of Object
What Class.forName() does?