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 situation
The code is just experimental right now and will be cleaned up in the future.
This method basically calls the setter of a PropertyDescriptor with the value of the getter PropertyDescriptor as an Argument this should only happen if their classes are the same, otherwise I treat them differently, however I have run into some issues with Lists, Sets, etc where List is the same as List which should not be the case. That's why I get the ParameterizedType of the Fields to compare their type parameters.
protected boolean translate(S source, T target) {
Class<?> readPropertyType = getter.getPropertyType();
Class<?> writePropertyType = setter.getPropertyType();
Type[] getterTypeParameters = null;
Type[] setterTypeParameters = null;;
try {
ParameterizedType getterParameterizedType = (ParameterizedType) source.getClass()
.getDeclaredField(getter.getName()).getGenericType();
getterTypeParameters = getterParameterizedType.getActualTypeArguments();
ParameterizedType setterParameterizedType = (ParameterizedType) target.getClass()
.getDeclaredField(setter.getName()).getGenericType();
setterTypeParameters = setterParameterizedType.getActualTypeArguments();
} catch (NoSuchFieldException | ClassCastException e) {}
try {
if (readPropertyType == writePropertyType && Arrays.equals(getterTypeParameters, setterTypeParameters)) {
setter.getWriteMethod().invoke(target, getter.getReadMethod().invoke(source));
return true;
}
... Handle other cases
} catch (Exception e) {
return false;
}
}
If you need more context, I made my git public: https://github.com/RaphaelEckmayr/AnotherJavaAutoMapper/blob/main/src/main/java/net/AJAM/Mapper/BaseTranslation.java
For reference this code takes about 0-1ms. However it is called for almost every field of a class.
Edits
More code and description of method added