MongoDB.live, free & fully virtual. June 9th - 10th. Register Now

Mongo-java-driver NullPointerException in getList

When using the mango-java driver: 3.12.1 getting NullPointerException exceptions when reading a collection containing null item from a document,

private <T> List<T> constructValuesList(final Object key, final Class<T> clazz, final List<T> defaultValue) {
    List<?> value = get(key, List.class);
    if (value == null) {
        return defaultValue;
    }

    for (Object item : value) {
        if (!clazz.isAssignableFrom(item.getClass())) { //NullPointerException if document contain list with null item
            throw new ClassCastException(format("List element cannot be cast to %s", clazz.getName()));
        }
    }
    return (List<T>) value;
}

how we can add small fix

if (item!=null && !clazz.isAssignableFrom(item.getClass()))

Hi @Vi_Os, welcome!

Could you provide the following information to further clarify the question:

  • A minimal reproducible example code
  • An example document schema to show the null item field
  • Error stack trace to indicate where it’s throwing the NullPointerException

Regards,
Wan.

Hi @wan
In our schema we can`t check value in collection because multiple service can update it
in our workflow we can change model but i think in mongo-java-driver check for NULL before check type is better solution

You can reproduce NPE with this code,

 Document npe = new Document();
        List<Integer> numbers = Arrays.asList(1, null);
        npe.put("numbers", numbers);
        List<Integer> read = npe.getList("numbers", Integer.class);

stack-trace

Exception in thread "main" java.lang.NullPointerException
	at org.bson.Document.constructValuesList(Document.java:381)
	at org.bson.Document.getList(Document.java:349)
	at MainApplication.main(MainApplication.java:56)

This will not throw NullPointerException:

List<Integer> read = (List<Integer>) npe.get("numbers");
System.out.println(read);     // prints [1, null]

Yes, we use Get method but there unchecked cast and no type control.
It no good solution because exist method getList, with small bug)