lil*_*tt8 0 java methods null static-analysis parameter-passing
我在下面有一个相当简单的测试用例.我可以向构造函数发送空值而没有任何问题或错误,但是当我尝试向方法发送空值时,它会出错:( error: incompatible types: <null> cannot be converted to int或者预期的任何类型).我不确定为什么会发生这种情况,而且我在很多地方看到过发送空值是可以接受的做法.在所有现实中我只需要空值,以便我可以将此示例泵入Soot和Spark进行静态分析,因此除了Spark-static分析中入口点的语义必要性之外,发送到方法的实际参数是无关紧要的.
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
}
}
Run Code Online (Sandbox Code Playgroud)
原语(例如,ints)不能采用nulls.如果您绝对必须使用null值,则应将方法参数定义为适当的包装类(例如,java.lang.Integerfor 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>()
}
Run Code Online (Sandbox Code Playgroud)