• Post Reply Bookmark Topic Watch Topic
  • New Topic

Type cast to Class Object  RSS feed

 
Chethan Sharma
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Program:
-----------
public static void main(String[] args) {
{
List names = new ArrayList();
names.add("Rams");
names.add("Shanker");

List numbers = new ArrayList();
numbers.add(new Integer("1"));
numbers.add(new Integer("2"));

printDet(numbers,"mumbers");
printDet(names,"names");
}
public static void printDet(List list,String type){
Class myclass;
if(type.equals("numbers")){
myclass = Integer.class;
}
else if(type.equals("names")){
myclass = String.class;
}
for(int i=0;i<list.size();i++){
System.out.println((myclass)list.get(i));
}

}
output:
--------
Error: 'myclass' is not resolved to a type...

Can anybody explain why this is not working?
Is there anyother way of coding to compile this example successfully?

Thanks,
 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not an advanced question. Moving...
 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
myclass is a variable, not a type.

If you have specific functionality for a particular type you can use method overloading to handle it. For example:
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Paul Sturrock:
If you have specific functionality for a particular type you can use method overloading to handle it.


No, that won't work. Overloading is resolved at compile time, not at runtime (in contrast to overriding).

But in the original example above, there is no need for casting, anyway. Println isn't overloaded, it simply gets an object as a parameter.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!