Get/Set Values for Static Fields and Properties
Custom .NET Framework DLL
With Javonet you can easily get or set a value for any static field or property from a class or structure from .NET Framework DLL by calling the "get(fieldOrPropertyName)" or "set(fieldOrPropertyName, newValue)" method on reference to .NET/Java type. Conversely, foreign instance types can be stored in Java variables using the dedicated Java type called NType.
As with the methods, value-typed results are automatically translated into Java types and reference results are returned as NObject\JObject objects.
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 set and get static field from this class:
// Todo: activate Javonet and add reference to .NET library
// get .NET type
NType sampleType = Javonet.getType("TestNamespace.TestClass");
// set static field
sampleType.set("MyStaticField", 10);
// get static field
Integer response = sampleType.get("MyStaticField");
// write response to console
System.out.println(response);
Standard .NET Framework DLL
To get static field from the standard .NET Framework DLL:
// Todo: activate Javonet
// get .NET DateTime class
NType dateTimeClass = Javonet.getType("System.DateTime");
// get datetime field
NObject nowDateObj = dateTimeClass.get("Now");
// invoke .NET method to get string
String response = nowDateObj.invoke("ToString");
// write response to console
System.out.println(response);
Was this article helpful?