Skip to content

Commit 0079ef1

Browse files
committed
Allow null elements in Document#getList (#1066)
JAVA-4837
1 parent ea09d64 commit 0079ef1

File tree

2 files changed

+8
-3
lines changed

2 files changed

+8
-3
lines changed

bson/src/main/org/bson/Document.java

+3-3
Original file line numberDiff line numberDiff line change
@@ -392,17 +392,17 @@ public <T> List<T> getList(final Object key, final Class<T> clazz, final List<T>
392392
// A ClassCastException will be thrown if an element in the list is not of type T.
393393
@SuppressWarnings("unchecked")
394394
private <T> List<T> constructValuesList(final Object key, final Class<T> clazz, final List<T> defaultValue) {
395-
List<?> value = get(key, List.class);
395+
List<T> value = get(key, List.class);
396396
if (value == null) {
397397
return defaultValue;
398398
}
399399

400400
for (Object item : value) {
401-
if (!clazz.isAssignableFrom(item.getClass())) {
401+
if (item != null && !clazz.isAssignableFrom(item.getClass())) {
402402
throw new ClassCastException(format("List element cannot be cast to %s", clazz.getName()));
403403
}
404404
}
405-
return (List<T>) value;
405+
return value;
406406
}
407407

408408
/**

bson/src/test/unit/org/bson/types/DocumentSpecification.groovy

+5
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@ class DocumentSpecification extends Specification {
6969
when:
7070
Document doc = Document.parse("{x: 1, y: ['two', 'three'], z: [{a: 'one'}, {b:2}], w: {a: ['One', 'Two']}}")
7171
.append('numberList', [10, 20.5d, 30L])
72+
.append('listWithNullElement', [10, null, 20])
7273
List<String> defaultList = ['a', 'b', 'c']
7374

7475
then:
@@ -84,6 +85,9 @@ class DocumentSpecification extends Specification {
8485
doc.getList('numberList', Number).get(0) == 10
8586
doc.getList('numberList', Number).get(1) == 20.5d
8687
doc.getList('numberList', Number).get(2) == 30L
88+
doc.getList('listWithNullElement', Number).get(0) == 10
89+
doc.getList('listWithNullElement', Number).get(1) == null
90+
doc.getList('listWithNullElement', Number).get(2) == 20
8791
}
8892

8993
def 'should return null list when key is not found'() {
@@ -103,6 +107,7 @@ class DocumentSpecification extends Specification {
103107
doc.getList('a', String, defaultList) == defaultList
104108
}
105109

110+
106111
def 'should throw an exception when the list elements are not objects of the specified class'() {
107112
given:
108113
Document doc = Document.parse('{x: 1, y: [{a: 1}, {b: 2}], z: [1, 2]}')

0 commit comments

Comments
 (0)