• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Liutauras Vilda
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Saloon Keepers:
  • Scott Selikoff
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
  • Frits Walraven
Bartenders:
  • Stephan van Hulst
  • Carey Brown

Type cast to Class Object

 
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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,
 
Bartender
Posts: 10336
Hibernate Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Not an advanced question. Moving...
 
Paul Sturrock
Bartender
Posts: 10336
Hibernate Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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:
 
author
Posts: 14112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
You save more money with a clothesline than dozens of light bulb purchases. Tiny ad:
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic