vendredi 12 mai 2017

How to invoke methods of objects with different types with same name and different return values?

I have a lot of classes generated by JAXB and I can not change them. I have to get the values of the properties for some of their objects in a pretty similar way and then populate table with them. Here I am giving the code for two such getter methods:

private String getPropertyIdentifierStringOrNull(IdentifierType obj)
{
    if(obj != null)
        return obj.getValue();
    else
        return null;
}

private XMLGregorianCalendar getPropertyXMLGregorianCalendarOrNull(DateType obj)
{
    if(obj != null)
        return obj.getValue();
    else
        return null;
}

DateType and IdentifierType do not have common supperclass, and as in this example code return values can be of different types.

I am trying to write one method instead of bunch of these. I've come up with this solution using generic method with the reflection:

@SuppressWarnings("unchecked")
private <T> T getPropertyOrNull(Object obj)
{
    if(obj != null)
    {
        try
        {
            return (T) obj.getClass().getMethod("getValue").invoke(obj);
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }
    return null;
}

Is this good way of doing this kind of calls or is there any better solution?





Aucun commentaire:

Enregistrer un commentaire