[JAVA-2758] ClassCastException in method Document#get(final Object key, final T defaultValue) when defaultValue is subType of T Created: 29/Jan/18 Updated: 28/Oct/23 Resolved: 22/May/18 |
|
| Status: | Closed |
| Project: | Java Driver |
| Component/s: | API |
| Affects Version/s: | None |
| Fix Version/s: | 3.8.0 |
| Type: | Bug | Priority: | Major - P3 |
| Reporter: | Daniel Fesenmeyer [X] | Assignee: | Jeffrey Yemin |
| Resolution: | Fixed | Votes: | 0 |
| Labels: | None | ||
| Remaining Estimate: | Not Specified | ||
| Time Spent: | Not Specified | ||
| Original Estimate: | Not Specified | ||
| Description |
|
The following code throws an unexpected ClassCastException when a value is found, i.e. the default value is not used:
The following complicated code works:
In my opinion, this method is useless (and dangerous) in the public API. If you want to provide such a functionality, you should consider to provide a method which also requires the class to cast to: Document#get(Object key, Class<T> clazz, T defaultValue) |
| Comments |
| Comment by Githook User [ 22/May/18 ] | |||||
|
Author: {'username': 'jyemin', 'name': 'Jeff Yemin', 'email': 'jeff.yemin@10gen.com'}Message: In org.bson.Document#get(Object key, T defaultValue), just cast to T | |||||
| Comment by Daniel Fesenmeyer [X] [ 30/Jan/18 ] | |||||
|
I think the second approach is more convenient, because method getObject(final Object key) would be a generic alternative to getInteger(final Object key), ... | |||||
| Comment by Jeffrey Yemin [ 29/Jan/18 ] | |||||
|
One other idea: change the implementation of the existing method to:
| |||||
| Comment by Jeffrey Yemin [ 29/Jan/18 ] | |||||
|
The current API is convenient for final (or should be final) classes like Integer, Boolean, Date, but I see how it's difficult to use properly for collections and maps, so thank you for bringing it up. Thinking about the API that you propose, one issue is that
generates a compiler warning for unsafe operations, because myCollection is generic. We could add a method like this to Document
but it would have to contain an unsafe cast to List<T>. |