Creating Instance Of Generic Object

Creating Instance Of Generic Object

Javonet allows you to create instances of generic objects. To initialize generic class first NType with expected generic type should be created. Next to initialize the instance of generic type call the “create()” method on NType object.

Important Notice that while initializing NType for generic class there is apostrophe with number of generic arguments provided which let’s Javonet recognize which generic class should be initialized. For example for List<T> class, the List<Strings> can be obtained by calling Javonet.getType(“List`1″,String”). As first argument we provide generic type name and number of generic arguments and as second argument the name of the type to be used as generic type. If class expects more then one generic type they should be passed as further arguments of getType method.

How to create instance of .NET generic class Dictionary<String,List<String>>

//Initialize List <String> type
NType typeList = Javonet.getType("List`1","String");
//Get String type
NType typeString = Javonet.getType("String");
//Initialize Dictionary<String,List<String>> type
NType type = Javonet.getType("Dictionary`2",typeString,typeList);

//Create instance of generic Dictionary
NObject newDict = type.create();

//Create instance of generic List
NObject newList = typeList.create();
//Add items to generic list
newList.invoke("Add","a");
newList.invoke("Add","b");

//Adding items to generic Dictionary passing string as key and generic List as value
newDict.invoke("Add","List1",newList);
newDict.invoke("Add","List2",newList);

//Retrieving dictionary item by string key
NObject result = newDict.getIndex("List1");

//Displaying second item from generic List retrieved from dictionary
System.out.println(result.getIndex(1)); //displays "b"

See Live Example!