Calling overloaded method passing null argument

You are browsing legacy Javonet 1.5 (Java<>.NET bridge for Windows) documentation. Use the left side menu or click here to switch to latest Javonet 2.0 documentation. Javonet 2.0 allows you to use any module from JVM, CLR, Netcore, Python, Ruby, Perl, NodeJS on Windows, Linux and MacOs from any application created in Java, Clojure, Groovy, Kotlin, C#, F#, J#, VB.NET, Python, Perl, Ruby, JavaScript, TypeScript, C++ and GoLang

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:

using System;

namespace TestNamespace
{
	public class TestClass2
	{
		public string MethodA(String arg)
		{
			return "Method with String argument called";
		}
		public string MethodA(Object arg)
		{
			return "Method with Object argument called";
		}
		public string MethodA(int? arg)
		{
			return "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:

I code in:
// Todo: activate Javonet and add reference to .NET library

// create instance
NObject sampleObject = Javonet.New("TestNamespace.TestClass2");

// call MethodA with String argument passing null
String response = sampleObject.invoke("MethodA", new NNull("String"));

// call MethodA with generic int? argument
String response2 = sampleObject.invoke("MethodA", new NNull("System.Nullable`[System.Int32]"));

// write response to console
System.out.println(response);
System.out.println(response2);
// expected output:
// System.String

See Live Example!