Uploaded image for project: 'Java Driver'
  1. Java Driver
  2. JAVA-2758

ClassCastException in method Document#get(final Object key, final T defaultValue) when defaultValue is subType of T

    • Type: Icon: Bug Bug
    • Resolution: Fixed
    • Priority: Icon: Major - P3 Major - P3
    • 3.8.0
    • Affects Version/s: None
    • Component/s: API
    • None

      The following code throws an unexpected ClassCastException when a value is found, i.e. the default value is not used:

      final Collection<String> myCollection = myDocument.get("myKey", Collections.emptySet());
      // throws: java.lang.ClassCastException: Cannot cast java.util.Collections$UnmodifiableSet to java.util.Collections$EmptySet
      

      The following complicated code works:

      final Collection<String> myCollection = document.get("myKey", Collections.unmodifiableSet(Collections.emptySet()))
      

      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)
      This method should cast to clazz instead of the defaultValue.getClass().

            Assignee:
            jeff.yemin@mongodb.com Jeffrey Yemin
            Reporter:
            danielFesenmeyer Daniel Fesenmeyer [X]
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: