Why casting (Object)null result to not null?

一个人想着一个人 提交于 2019-12-12 14:31:44

问题


I use java 7, and I create a varargs method

public class JavaApplicationTest {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        addBundleMessage("b", Integer.SIZE, "key", (Object) null);
    }

    public static void addBundleMessage(String bundleName, Integer severity, String key, Object... params) {
        if (params == null)
            System.out.println("params Is null");
        else
            System.out.println("Params not null");
    }
}

If I don't cast the object, the IDEs Netbeans or Eclipse complains but it compiles :

non-varargs call of varags method with inexact argument type for last parameter

When No cast : it display params Is null

When I cast null to (Object) it display Params not null

When I cast null to (Object[]) it display params Is null

Is it normal behavior ?


回答1:


Yes, that is "normal" behaviour.

The confusion comes from varargs being bolted on to the language later and being implemented using an array as the "real parameter" to hold the variable number of parameters.

public static void addBundleMessage(String bundleName, Integer severity,
   String key, Object... params) {

is almost the same as

public static void addBundleMessage(String bundleName, Integer severity,
   String key, Object[] params) {

and under the hoods, the params are passed wrapped as an Object[].

However, you still have the option to pass in that array yourself.

If you use (Object[]) null, you get a parameter (that is null).

If you use (Object) null, it uses the varargs method, so it passes in an array to hold the parameters (of which there is only one which is null).

For "normal use" of a varargs method, params will never be null. The "worst" you can get is an empty array (if there are no arguments at all).




回答2:


The casting won't do anything to the null, it will just help the compiler choose between the overloaded methods. As you are using a multi-param method, the params will be an array so your null test on it is not relevant.




回答3:


When No cast : it display params Is null

The varargs are null in this case, so you get a null

When I cast null to (Object) it display Params not null

The varargs contains one object (per your casting) which is null

When I cast null to (Object[]) it display params Is null

The varargs are the Object[] you passed, which is null




回答4:


Without the cast is the same as with a cast to Object[]. You are passing a null argument array, so params is null.

When you cast the null to Object, you are passing a single null argument, so params is not null, it is instead an Object[1], whose only element is null.



来源:https://stackoverflow.com/questions/11097664/why-casting-objectnull-result-to-not-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!