Get/Set Values for Instance 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

To set or get values of instance fields and properties, get or create an instance of the object from .NET Framework DLL, and call "get(fieldOrPropertyName)" or "set(fieldOrPropertyName,newValue)" methods on NObject\JObject containing this field. 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 instance field from this class:

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

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

// set instance field
sampleObject.set("MyInstanceField", 11);

// get static field
Integer response = sampleObject.get("MyInstanceField");

// write response to console
System.out.println(response);

See Live Example!