orika-mapper / orika

Simpler, better and faster Java bean mapping framework
http://orika-mapper.github.io/orika-docs/
Apache License 2.0
1.29k stars 268 forks source link

NPE while mapAsList invocation #386

Open Denis-D-M opened 2 years ago

Denis-D-M commented 2 years ago

Hello everyone! This is my first issue report, so don't judge strictly.

I have a list that is null.

And the issue appears when I try to use mapAsList(...) method:

public <S, D> List<D> mapAsList(final Iterable<S> source, final Class<D> destinationClass) {
        return mapAsList(source, elementTypeOf(source), TypeFactory.valueOf(destinationClass));
    }

There is another method invocation - elementTypeOf(source):

 private <T> Type<T> elementTypeOf(final Iterable<T> object) {
        try {
            Method iterator = object.getClass().getMethod("iterator");
            Type<Iterable<T>> type = TypeFactory.valueOf(iterator.getGenericReturnType());
            return type.getNestedType(0);
        } catch (SecurityException e) {
            throw new IllegalStateException(e);
        } catch (NoSuchMethodException e) {
            throw new IllegalStateException(e);
        }
    }

Which causes NPE to be thrown because of object.getClass().

But the reason I've used this method is null check inside of inner method - mapAsCollection, which is invoked by mapAsList(...) after elemtTypeOf(source):

    private <S, D> Collection<D> mapAsCollection(final Iterable<S> source, final Type<S> sourceType, final Type<D> destinationType,
                                                 final Collection<D> destination, final MappingContext context) {

        if (source == null) {
            return null;
        }
        ElementStrategyContext<S, D> elementContext = new ElementStrategyContext<S, D>(context, sourceType, destinationType);
        for (final S item : source) {
            if (item != null) {
                destination.add(mapElement(item, elementContext));
            }
        }
        return destination;
    }

So, I found this null check is useless.