lundi 19 août 2019

Get Generic Type using Reflection

class Things{   
  Thing<Vegetables> veggies;
  Thing<Fruits> fruits;

   public Things(String name,
                Class<V> type) {
    this.name = name;
    this.valueClass = type;
}
....
}

Using reflection I want to create an object for each field in this class and set them. But I cant get and set the type, here is my code:

  Field[] allFields = Things.class.getDeclaredFields();
    for (Field field : allFields) {
            Thing thing =  new Thing(field.getName(),field.getGenericType().getTypeName().getClass());       
    }
}

field.getGenericType().getTypeName().getClass()

Returns String and not Vegetables or Fruits (Rightly so) How can I get the generic type of the field using Reflection?

Note: The so called dublicate question is not answering or asking the same thing





Aucun commentaire:

Enregistrer un commentaire