java - 将 null 作为参数发送给 Java 中的方法

标签 java methods null parameter-passing static-analysis

下面我有一个相当简单的测试用例。我可以将空值发送到构造函数,没有任何问题或错误,但是当我尝试将空值发送到方法时,会出错: 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/

相关文章:

java - Spring Data 2.0.x AuditorAware getCurrentUser 方法抛出 AbstractMethodError

java - 在使用 FBManager 创建的数据库上设置默认字符集

java - 有没有办法在不到 O(n) 的时间内连接 Java 字符串?

java - 自动定时器@Schedule Java EE

python类方法和继承

sql-server - SQL在日期之间选择,但在开始和结束日期为空时显示所有

c# - C# 中的 "static method"是什么?

java - 如何在java方法中将数组作为参数传递?

jquery - 无法使用 jQuery AJAX 将 null 传递到服务器。服务器收到的值是字符串 "null"

php - mysql查询不选择空列