Reputation: 5200
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:
List<String>
as List
when calling the .GetType()
method.GetGenericType()
method, the actual type of T
cannot be instantiated, as the method does not provide any function for that purpose. <>
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
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