Using nested types
Nested types are the classes defined within other class or struct. Javonet is able to create the instance of nested type, pass nested type as Type argument, set nested type to field or property and use nested types as generic arguments for methods and classes.
More about nested types you can read in MSDN documentation: Nested Types
Assuming we have a custom .NET Framework DLL with the following classes 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();
}
}
}
And
namespace TestNamespace
{
public class Container
{
public class Nested
{
public Nested() { }
}
}
}
To reference nested type with full namespace the name of the nested class should be prefixed with namespace, name of parent class and "+" sign. For example the "Nested" class defined above could be access using following path "TestNamespace.Container+Nested". Following examples show how to initialize and work with nested types using full namespace.
// Todo: activate Javonet and add reference to .NET library
// create instance
NObject sampleObject = Javonet.New("TestNamespace.TestClass");
//Getting nested type
NType nestedTypeObj = Javonet.getType("TestNamespace.Container+Nested");
//Creating instance of nested type
NObject nestedTypeInstanceObj = Javonet.New("TestNamespace.Container+Nested");
//Passing nested type as method argument
sampleObject.invoke("PassTypeArg", nestedTypeObj);
//Creating generic object with nested type as generic argument
NObject genList = Javonet.getType("List`1", nestedTypeObj).create();
//Calling generic method with nested type as generic argument
sampleObject.generic(nestedTypeObj).invoke("MyGenericMethod", nestedTypeInstanceObj);
Was this article helpful?