From 0079ef182b52b32106599b21c46c9e32d5ccc658 Mon Sep 17 00:00:00 2001 From: Jeff Yemin Date: Thu, 12 Jan 2023 10:27:49 -0500 Subject: [PATCH] Allow null elements in Document#getList (#1066) JAVA-4837 --- bson/src/main/org/bson/Document.java | 6 +++--- .../test/unit/org/bson/types/DocumentSpecification.groovy | 5 +++++ 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/bson/src/main/org/bson/Document.java b/bson/src/main/org/bson/Document.java index 5c44b935597..88a7bad07cd 100644 --- a/bson/src/main/org/bson/Document.java +++ b/bson/src/main/org/bson/Document.java @@ -392,17 +392,17 @@ public List getList(final Object key, final Class clazz, final List // A ClassCastException will be thrown if an element in the list is not of type T. @SuppressWarnings("unchecked") private List constructValuesList(final Object key, final Class clazz, final List defaultValue) { - List value = get(key, List.class); + List value = get(key, List.class); if (value == null) { return defaultValue; } for (Object item : value) { - if (!clazz.isAssignableFrom(item.getClass())) { + if (item != null && !clazz.isAssignableFrom(item.getClass())) { throw new ClassCastException(format("List element cannot be cast to %s", clazz.getName())); } } - return (List) value; + return value; } /** diff --git a/bson/src/test/unit/org/bson/types/DocumentSpecification.groovy b/bson/src/test/unit/org/bson/types/DocumentSpecification.groovy index fa676bac5ee..8d725654c9d 100644 --- a/bson/src/test/unit/org/bson/types/DocumentSpecification.groovy +++ b/bson/src/test/unit/org/bson/types/DocumentSpecification.groovy @@ -69,6 +69,7 @@ class DocumentSpecification extends Specification { when: Document doc = Document.parse("{x: 1, y: ['two', 'three'], z: [{a: 'one'}, {b:2}], w: {a: ['One', 'Two']}}") .append('numberList', [10, 20.5d, 30L]) + .append('listWithNullElement', [10, null, 20]) List defaultList = ['a', 'b', 'c'] then: @@ -84,6 +85,9 @@ class DocumentSpecification extends Specification { doc.getList('numberList', Number).get(0) == 10 doc.getList('numberList', Number).get(1) == 20.5d doc.getList('numberList', Number).get(2) == 30L + doc.getList('listWithNullElement', Number).get(0) == 10 + doc.getList('listWithNullElement', Number).get(1) == null + doc.getList('listWithNullElement', Number).get(2) == 20 } def 'should return null list when key is not found'() { @@ -103,6 +107,7 @@ class DocumentSpecification extends Specification { doc.getList('a', String, defaultList) == defaultList } + def 'should throw an exception when the list elements are not objects of the specified class'() { given: Document doc = Document.parse('{x: 1, y: [{a: 1}, {b: 2}], z: [1, 2]}')