简体   繁体   中英

Should a java method accepting long value accept a Integer object?

I have a method that accepts a long primitive value and do some processing based on it. It was originally int and changed later. The code where this method is actually called was calling this method with Integer, which was ok earlier becouse of java Autoboxing and Unboxing .

But after this has been changed to long, my code doesn't show any compile time error while building as i expected. Now if i change it to int instead of Integer, it shows compile time error but not with Integer.

Why is this happening ?

EDIT :

class ABC {
   public Customer customerExists(long cid) throws Exception {
   ...
   }
}

class XYZ {
    public void method() {
       Integer customerId = null;
       ...
       customerExists(customerId);
       ...
    }
}

This should be a compile time error according to me but its not.

Java Version - openjdk version "1.8.0_31" OpenJDK Runtime Environment (build 1.8.0_31-b13) OpenJDK 64-Bit Server VM (build 25.31-b07, mixed mode)

you can test some changes, to improve your code, look at this piece of code :

class ABC {
   public Customer customerExists(Number cid) throws Exception {
   ...
   if( cid instanceof Integer) {
     cid.intValue().....
   }


   }
}

class XYZ {
    public void method() {
       Integer customerId = null;
       ...
       customerExists(customerId);
       ...
    }
}

so you can pass whatever kind of number, take a look at this class to convert in any type number that you need. ( number class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM