Using Nested Types

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: http://msdn.microsoft.com/en-us/library/ms173120.aspx

Sample of nested type

namespace MyApp 
{
    public class Container
    {
        public class Nested
        {
            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 “MyApp.Container+Nested”. Following examples show how to initialize and work with nested types using full namespace.

Important: If nested type class name is unique within the loaded assemblies, you can use just the class name. For example “Nested” and work with it as it was regular type.

Sample of using nested types in Java with full namespace

//Getting nested type
NType nestedTypeObj = Javonet.getType("MyApp.Container+Nested");

//Creating instance of nested type
NObject nestedTypeInstanceObj = Javonet.New("MyApp.Container+Nested");

//Passing nested type as method argument
sampleObj.invoke("MethodWithTypeArg", 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
sampleObj.generic(nestedTypeObj).invoke("GenricMethod");

See Live Example!