1

I decompiled one of my java .class files and saw this line of code

new ResponseModel("Reset Complete", false, (LinkedHashMap)null)

The line corresponds to

new ResponseModel("Reset Complete", false, null);

Why was the null parameter casted? Is it just my decompiler hinting the parameter type?

Amanuel Nega
  • 1,899
  • 1
  • 24
  • 42

1 Answers1

3

Immagine you've overloaded a method:

public class Foo {

    public void something (String s) { ... }
    public void something (List l) { ... }
}

Invoking something with a null argument is now ambiguous. To bind the invocation to either method, you need to cast the null value, giving it a type:

new Foo().something((String)null);
new Foo().something((List)null);

As this class may be different at runtime than on compile time (on compile time, the method may not be overloaded, but on runtime the class is a newer version which has an overloaded method), the compiler makes it explicit in the bytecode to prevent ambiguousness later.

Peter Walser
  • 15,208
  • 4
  • 51
  • 78