samedi 14 août 2021

Java: Get ParameterizedType from PropertyDescriptor

Problem

I am working on a project where I have to deal a lot with reflections and the performance needs to be improved. This method is called very often and this part seems inefficient to me as I need to get the Field by another reflection, which I only need to compare the type parameters of two Objects (I don't know how inefficient it really is tbh). Because I want List.class != List.

Even finding out whether a Class has type parameter without having to do crazy reflections should be enough.

Current code for getting the type parameters

protected boolean translate(S source, T target) {
    try {
            ParameterizedType paramType = (ParameterizedType) source.getClass()
                 .getDeclaredField(propertyDescriptor.getName()).getGenericType();
            Type[] clazzes = paramType.getActualTypeArguments();
            System.out.println(clazzes);
    } catch (NoSuchFieldException | ClassCastException e) {

    }

    ...
}

For reference this code takes about 0-1ms. However it is called for almost every field of a class.





Aucun commentaire:

Enregistrer un commentaire