Invoking Static 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

To invoke the static method, first get the particular type and call invoke providing method arguments.
Assuming we have a custom JAR library with the following class inside:

public class TestClass {
    public TestClass() {
    }

    public static int MyStaticField;

    public int MyInstanceField;

    public static String SayHello(String name) {
        return "Hello " + name;
    }

    public static int MethodExpectingPrimitiveInt(int arg) {
        return arg * 2;
    }

    public static int MethodExpectingClassInteger(Integer arg) {
        return arg * 2;
    }

    public int MultiplyByTwo(Integer arg) {
        return arg * 2;
    }

    public <T> T MyGenericMethod(T arg1)
    {
        return arg1;
    }
}

To invoke static method from this class:

I code in:
// Todo: activate Javonet

// add reference to library
Javonet.AddReference(resourcesDirectory + @"\TestClass.jar");

// get Java type
JType sampleType = Javonet.GetType("TestClass");

// call static method
string response = sampleType.Invoke<string>("SayHello", "Student");

// write result to console
Console.WriteLine(response);

The invoke method allows you to call any static or method with or without arguments. Value-type arguments are automatically translated to appropriate types, and you can also pass referenced arguments. If method has no arguments you just call it using Invoke("methodName"). If called method expects arguments you can pass them as arguments to Invoke method.

Any calls to .NET or Java objects using Javonet can be shortened and simplified using Javonet Fluent interface.

See Live Example!