下面我有一个相当简单的测试用例。我可以将空值发送到构造函数,没有任何问题或错误,但是当我尝试将空值发送到方法时,会出错: error: incompatible types: <null> cannot be converted to int
(或任何预期的类型)。我不太确定为什么会发生这种情况,而且我在很多地方都看到发送空值是可以接受的做法。实际上,我只需要空值,以便我可以将此示例放入 Soot 和 Spark 中进行静态分析,因此发送到方法的实际参数除了 Spark 静态分析中入口点的语义必要性之外是无关紧要的。
public class Test {
public Test(Object var1, Object var2) {
//do irrelevant stuff here with var1 and var2
}
public void api1(int x, int y) {
// do irrelevant stuff with x and y
}
public List<String> api2(String x, int y, boolean a) {
// do irrelevant stuff with x, y, and a and return a new ArrayList<String>()
}
}
public class Main {
public static void main(String[] args) {
Test usingVars = new Test(1, 2); // works, compiles and no errors
Test usingNulls = new Test(null, null); // works, compiles and no errors
/**
* usingVars will obviously work and not complain at all
*/
usingVars.api1(1, 2); // works, compiles and no errors
usingVars.api2("test", 1, false); // works, compiles and no errors
/**
* usingNulls should work, but throws this error on compilation:
* error: incompatible types: <null> cannot be converted to int
*/
usingNulls.api1(null, null); // should work, doesn't compile errors out
usingNulls.api2(null, null, null); // should work, doesn't compile errors out
}
}
最佳答案
基元(例如,int
)不能采用null
。如果您绝对必须使用 null
值,则应该将方法参数定义为适当的包装类(例如,java.lang.Integer
代表 int
):
public Test(Integer var1, Integer var2) {
//do irrelevant stuff here with var1 and var2
}
public void api1(Integer x, Integer y) {
// do irrelevant stuff with x and y
}
public List<String> api2(String x, Integer y, Boolean a) {
// do irrelevant stuff with x, y, and a and return a new ArrayList<String>()
}
关于java - 将 null 作为参数发送给 Java 中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30060607/