Arnold Zahrneinder
Arnold Zahrneinder

Reputation: 5200

Generic type instantiation using reflection

Assuming the following data model:

public Test extends CanDeserialize {
   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 abstract CanDeserialize{
    public void deserialize(String object){
        Field[] fields = this.getClass().getDeclaredFields();
    } 

How can I instantiate an object for the userRoles??

Upvotes: 0

Views: 78

Answers (1)

Transcendent
Transcendent

Reputation: 5755

In Java you can do the following:

List list = new ArrayList();
list.add("Some Values");

Now assuming you have a List<String> you can set value using reflection through getting fields (as you did) and then

fields[0].set(this, list); // in your example there's 1 field only, so the index is 0.

This works because in Java, any generics eventually lead to Object type. And yeah that means you don't need reflection to initialize that.

Upvotes: 1

Related Questions