Calling generic methods
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
With Javonet you can very easily invoke any generic instance or static method. To call a generic method, you need to provide types that will be used during the method invocation. Those types can be passed as an instance of NType objects initialized with particular .NET types.
Assuming we have a custom .NET Framework DLL with the following class inside:
using System;
namespace TestNamespace
{
public class TestClass
{
public TestClass() { }
~TestClass()
{
Console.WriteLine("Displaying object from .NET destructor message");
}
public static int MyStaticField { get; set; }
public int MyInstanceField { get; set; }
public static string SayHello(string name)
{
return "Hello " + name;
}
public int MultiplyByTwo(int arg)
{
return arg * 2;
}
public T MyGenericMethod<T>(T arg1)
{
return arg1;
}
public K MyGenericMethodWithTwoTypes<T, K>(T arg1)
{
return default(K);
}
public void MethodWithRefArg(ref int arg)
{
arg = arg + 44;
}
public string PassTypeArg(Type myType)
{
return myType.ToString();
}
public string MethodWithEnumArg(SampleEnum value)
{
return value.ToString();
}
}
}
To use generic methods from this class:
I code in:
// Todo: activate Javonet and add reference to .NET library
// create instance
NObject sampleObject = Javonet.New("TestNamespace.TestClass");
// invoke generic method with one type
String response1 = sampleObject.generic(Javonet.getType("String")).invoke("MyGenericMethod", "sample");
// invoke generic method with two types
Integer response2 = sampleObject.generic(Javonet.getType("String"), Javonet.getType("Int32")).invoke("MyGenericMethodWithTwoTypes", "sample");
// write response to console
System.out.println(response1);
System.out.println(response2);
- Create an instance of our GenericSample class.
- Using the generic method, initialize the generic method invocation by passing one or many generic types of arguments.
- Invoke your method with a sample argument.
Javonet.getType(typeName) returns an instance of NType object attached to a specific .NET type. The instruction NType myType = Javonet.getType("String") is the Java equivalent of the .NET Type myType = typeof(String).
Was this article helpful?