Why doesn't Java autoboxing extend to method invocations of methods of the autoboxed types?

前端 未结 8 1028
时光取名叫无心
时光取名叫无心 2020-12-30 18:19

I want to convert a primitive to a string, and I tried:

myInt.toString();

This fails with the error:

int cannot be derefere         


        
相关标签:
8条回答
  • 2020-12-30 19:03

    One other way to do it is to use:

    String.valueOf(myInt);
    

    This method is overloaded for every primitive type and Object. This way you don't even have to think about the type you're using. Implementations of the method will call the appropriate method of the given type for you, e.g. Integer.toString(myInt).

    See http://java.sun.com/javase/6/docs/api/java/lang/String.html.

    0 讨论(0)
  • 2020-12-30 19:17

    seems like a shortcoming of the specification to me

    There are more shortcomings and this is a subtle topic. Check this out:

    public class methodOverloading{
       public static void hello(Integer x){
          System.out.println("Integer");
       }
    
       public static void hello(long x){
          System.out.println("long");
       }
    
       public static void main(String[] args){
          int i = 5;
          hello(i);
       }
    }
    

    Here "long" would be printed (haven't checked it myself), because the compiler choses widening over autoboxing. Be careful when using autoboxing or don't use it at all!

    0 讨论(0)
提交回复
热议问题