繁体   English   中英

接受长值的java方法是否应该接受Integer对象?

[英]Should a java method accepting long value accept a Integer object?

我有一个接受长原始值并根据它进行一些处理的方法。 它最初是int型,后来又更改了。 实际调用此方法的代码是使用Integer调用此方法的,因为Java Autoboxing和Unboxing较早,所以可以。

但是在将其更改为很长的时间之后,我的代码在构建时并没有显示任何编译时错误,正如我所期望的那样。 现在,如果我将其更改为int而不是Integer,它将显示编译时错误,但不会显示Integer。

为什么会这样呢?

编辑:

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

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

根据我的说法,这应该是编译时错误,但不是。

Java版本-openjdk版本“ 1.8.0_31” OpenJDK运行时环境(内部版本1.8.0_31-b13)OpenJDK 64位服务器VM(内部版本25.31-b07,混合模式)

您可以测试一些更改,以改善您的代码,请看下面这段代码:

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);
       ...
    }
}

因此,您可以传递任何类型的数字,看看此类可转换为所需的任何类型数字。 数字类

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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