0

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??

2
  • Didn't you just ask this same question about 2 hours ago? Or am I confused? Commented Jan 14, 2017 at 22:14
  • @HovercraftFullOfEels: You are surly confused :D (no disrespect :) ) Commented Jan 14, 2017 at 22:16

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.