Skip to content

Commit 847d648

Browse files
committed
JAVA-2758: Cast to T instead of using Class#cast
In org.bson.Document#get(Object key, T defaultValue), just cast to T instead of calling Class#cast on defaultValue's class.
1 parent 1746ad5 commit 847d648

File tree

2 files changed

+34
-2
lines changed

2 files changed

+34
-2
lines changed

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

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -154,9 +154,8 @@ public <T> T get(final Object key, final Class<T> clazz) {
154154
@SuppressWarnings("unchecked")
155155
public <T> T get(final Object key, final T defaultValue) {
156156
notNull("defaultValue", defaultValue);
157-
Class<T> clazz = notNull("clazz", (Class<T>) defaultValue.getClass());
158157
Object value = documentAsMap.get(key);
159-
return value == null ? defaultValue : clazz.cast(value);
158+
return value == null ? defaultValue : (T) value;
160159
}
161160

162161
/**

bson/src/test/unit/org/bson/DocumentTest.java

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,10 @@
2929
import org.bson.json.JsonReader;
3030
import org.junit.Test;
3131

32+
import java.util.Arrays;
33+
import java.util.Collections;
34+
import java.util.List;
35+
3236
import static java.util.Arrays.asList;
3337
import static org.bson.codecs.configuration.CodecRegistries.fromCodecs;
3438
import static org.bson.codecs.configuration.CodecRegistries.fromProviders;
@@ -75,6 +79,35 @@ public void toJsonShouldReturnEquivalent() {
7579
document);
7680
}
7781

82+
// Test in Java to make sure none of the casts result in compiler warnings or class cast exceptions
83+
@Test
84+
public void shouldGetWithDefaultValue() {
85+
// given
86+
Document d = new Document("x", 1)
87+
.append("y", Collections.singletonList("one"))
88+
.append("z", "foo");
89+
90+
// when the key is found
91+
int x = d.get("x", 2);
92+
List<String> y = d.get("y", Arrays.asList("three", "four"));
93+
String z = d.get("z", "bar");
94+
95+
// then it returns the value
96+
assertEquals(1, x);
97+
assertEquals(Arrays.asList("one"), y);
98+
assertEquals("foo", z);
99+
100+
// when the key is not found
101+
int x2 = d.get("x2", 2);
102+
List<String> y2 = d.get("y2", Arrays.asList("three", "four"));
103+
String z2 = d.get("z2", "bar");
104+
105+
// then it returns the default value
106+
assertEquals(2, x2);
107+
assertEquals(Arrays.asList("three", "four"), y2);
108+
assertEquals("bar", z2);
109+
}
110+
78111
@Test
79112
public void toJsonShouldTakeACustomDocumentCodec() {
80113

0 commit comments

Comments
 (0)