Calling Overloaded Method Passing Null Argument

Calling Overloaded Method Passing Null Argument

In some cases you might need to call a method – that has multiple overloads with the same number of arguments – passing null. Considering following case:

public void MethodA(String arg)
{
    Console.Out.WriteLine("Method with String argument called");
}
public void MethodA(Object arg)
{
    Console.Out.WriteLine("Method with Object argument called");
}
public void MethodA(int? arg)
{
    Console.Out.WriteLine("Method with nullable int argument called");
}

If you call MethodA passing “null” as argument .NET side will not be able to resolve which method should be called as in both overloads null can be passed. Ambigous invocation exception will be thrown. To overcome this issue Javonet introduces “NNull” type which allows to pass type-specific null value.

How to call .NET method passing type-specific null value

//To call MethodA with String argument passing null use the following syntax
sampleObj.invoke("MethodA",new NNull("String"));

//Or to call overload with generic int? argument
sampleObj.invoke("MethodA",new NNull("Nullable`[System.Int32]"));

See Live Example!