Using enum type
To use .NET enums in your Java project, javonet API provides special NEnum type.
Using this class you can keep the reference of particular enum value, get/set the enum value, pass the enum value as method argument or compare enum values.
To initialize reference to .NET enum type you can use the NEnum(String enumTypeName, String enumValue) constructor. As first argument you must provide enum type name with or without namespace.
When namespace is not provided Javonet will automatically lookup the enum type in all loaded assemblies, if there is only one type with provided name it will be used.
In second argument selected enum value should be provided.
Assuming we have a custom .NET Framework DLL with the following enum inside:
public enum SampleEnum
{
ValueOne,
ValueTwo,
ValueThree
}
Enum usage:
// Todo: activate Javonet and add reference to .NET library
// create instance of enum value
NEnum sampleEnumValueOne = new NEnum("SampleEnum", "ValueOne");
// get value name
String response = sampleEnumValueOne.getValueName();
// get enum value
Integer response2 = sampleEnumValueOne.getValue();
// write response to console
System.out.println(response);
System.out.println(response2);
How to pass enum as method argument:
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 enum as method argument:
// Todo: activate Javonet and add reference to .NET library
// create instance
NObject sampleObject = Javonet.New("TestNamespace.TestClass");
// create instance of enum value
NEnum sampleEnumValueOne = new NEnum("SampleEnum", "ValueTwo");
// invoke method with enum argument
String response = sampleObject.invoke("MethodWithEnumArg", sampleEnumValueOne);
// write response to console
System.out.println(response);
Was this article helpful?