Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get generic type from object list java

I had custom converter for dozer framework

constom converter called for generic type list source and generic type list destination

public class ListCommonCustomConverter implements ConfigurableCustomConverter{
  public Object convert(Object destination, Object source, Class<?> destinationClass, Class<?> sourceClass) {
    log.info("Inside CommonCustomConverter :: convert");
    // Need to fine generic type of list
    return null;
  }
}

Eg: if List<Person> passed as destination for converter i need to get Person class from destination object inside converter method.

Thank in Advance.

like image 358
Ramakrishna Avatar asked Aug 15 '26 05:08

Ramakrishna


1 Answers

You could get type info from a generic type by calling getClass().getGenericInterfaces() if your class was declared like:

public class ListCommonCustomConverter implements ConfigurableCustomConverter<Person>

But since this converter is not parameterized, you could do a trick:

public interface CustomConverterWithTypeInfo<T> extends ConfigurableCustomConverter{
}


public class ListCommonCustomConverter implements CustomConverterWithTypeInfo<Person>{
    public Object convert(Object destination, Object source, Class<?> destinationClass, Class<?> sourceClass) {
        Class<?> myClass = (Class)((ParameterizedType)getClass().getGenericInterfaces()[0]).getActualTypeArguments()[0];
        //...
    }
}

Or you could simply do:

List<?> list = (List)destination;
if(!list.isEmpty()){
     Class<?> myClass = list.get(0).getClass();
}
like image 179
Andrey Chaschev Avatar answered Aug 17 '26 18:08

Andrey Chaschev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!