Parameter class casting problem

The question is: how to get the right method based on the type of the parameter passed?

Here is the code:

publicclass Test{

publicstaticvoid main(String[] args){

Integer l = 57;// automatic boxing

Object o = 43;// automatic boxing and widening casting (?)

print( l );// OK: calls Integer

print( o );// calls Object: not what I want, but could be

print( (Integer)o );// OK: calls Integer

print( Integer.class.cast(o) );// OK: calls Integer

print( o.getClass().cast(o) );// NOT OK: dinamic casting does't work?

}

staticvoid print( Integer l ){

System.out.println("Integer: " + l.toString());

}

staticvoid print( Object o ){

System.out.println("Object: " + o.toString() +" (" + o.getClass().toString() +")");

}

}

[1671 byte] By [maxmasea] at [2007-10-3 3:00:38]
# 1

Method overloads are resolved at compile time; meaning only the compile time type of the expression used as parameter is taken into account.

Class<T>.cast(Object)

returns T.

Class<Integer>.cast returns Integer, so the first overload is chosen.

Class<Object>.cast returns Object, so here the second overload is chosen.

Lokoa at 2007-7-14 20:50:14 > top of Java-index,Java Essentials,Java Programming...