mardi 3 mai 2016

Obtain generic type of a Field using relection

Is there a way to obtain the generic type of a field in Java?

I have following object variables:

protected ScheduleView<WantedClass> scheduleLine1;
protected ScheduleView<SomeOtherClass> scheduleLine2;

Now I try using reflection to obtain all the object variables who have ScheduleView as type with WantedClass as generic type:

Arrays.asList(this.getClass().getDeclaredFields()).stream().map(field -> {
    ScheduleView<WantedClass> retValue = null;

    System.out.println(field.getGenericType()); // prints control.ScheduleView<dto.WantedClass>

    try {
        if (field.getType() == ScheduleView.class) { // here I also want to check if the generic type is WantedClass
            retValue = (ScheduleView<WantedClass>) field.get(this);
        } else {
            retValue = null;
        }
    } catch (IllegalAccessException e) {
        retValue = null;
    } finally {
        return retValue;
    }
}).filter(scheduleView -> scheduleView != null).forEach(scheduleView -> {
        /* some more code */
});

The thing is I also want to check in the if-Statement if the generic type is WantedClass. I also tried using the method getGenericType() but it seems something like this is not possible:

field.getGenericType() == ScheduleView<WantedClass>.class

So is there a way to get the generic type of a field?





Aucun commentaire:

Enregistrer un commentaire