Search code examples
javanullmethod-signature

How can I make a method take a null value?


If you have two overloaded methods like so:

public void methodName(File file){}
public void methodName(String string){}

If you try to call methodName with null you will get an error saying that it's ambiguous which is understandable because it doesn't know which method to do.

I know that you can just cast the null: methodName((String) null) but how can I create a method specifically to handle the situations where you call methodName(null)?

Something like this:

public void methodName(null null){}

How can I make a method which must take a null?


Solution

  • As you've seen, the compiler can't resolve two methods that take different kinds of objects when you pass null.

    The only way around this is either typecast, like you have done, or to have a method that takes a generic Object type and attempts to downcast:

    public void methodName( Object object ) {
        if ( object == null ) {
            // do something with null
        } else if ( object instanceof File ) {
            // do something with ((File)object)
        } else {
            // do something else
        }
    }
    

    Writing code that looks like this tends to be viewed as smelly, and for good reason. It gets complicated quickly, is difficult to maintain, etc. Your best bet is to typecast or to change your method signatures so that you (and the compiler) always know which function should be called to handle a specific null object.