samedi 14 janvier 2017

Generic type instantiation using reflection

Assuming the following data model:

public Test {
   private List<String> userRoles; 
   ...
} 

When requiring to deserialize the object manually and having to instantiate an object for the userRole, the following problems happen:

  1. Java reflection recognizes List<String> as List when calling the .GetType() method
  2. When calling .GetGenericType() method, the actual type of T cannot be instantiated, as the method does not provide any function for that purpose.
  3. Extracting the type from inside the <> and instantiating through Class.fromClass(...) may cause problems as the generic type maybe very complex, for example Pair<Pair<String,int>, Pair<String,int>>

Assuming that deserialization takes place inside of the class as follows:

public Test{
    public void deserialize(String object){
        Field[] fields = this.getClass().getDeclaredFields();
    } 

How can I instantiate an object for the userRoles??





Aucun commentaire:

Enregistrer un commentaire