Get/Set Values for Static Fields and Properties
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
Custom JAR library
With Javonet you can easily get or set a value for any static field or property from a class or structure from JAR library by calling the "get(fieldOrPropertyName)" or "set(fieldOrPropertyName, newValue)" method on reference to .NET/Java type. Conversely, foreign instance types can be stored in C# variables using the dedicated Java type called NType.
As with the methods, value-typed results are automatically translated into C# types and reference results are returned as NObject\JObject objects.
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 set and get static field from this class:
// Todo: activate Javonet
// add reference to library
Javonet.AddReference(resourcesDirectory + @"\TestClass.jar");
// get Java type
JType sampleType = Javonet.GetType("TestClass");
// set static field
sampleType.Set("MyStaticField", 10);
// get static field
int response = sampleType.Get<int>("MyStaticField");
// write result to console
Console.WriteLine(response);
Standard JAR library
To get static field from the standard JAR library:
// Todo: activate Javonet
// get Java type
JType sampleType = Javonet.GetType("java.lang.Math");
// get static field
double response = sampleType.Get<double>("PI");
// write result to console
Console.WriteLine(response);
Was this article helpful?