Uploaded image for project: 'Commons Collections'
  1. Commons Collections
  2. COLLECTIONS-747

MultiKey.getKeys class cast exception

    XMLWordPrintableJSON

Details

    • Bug
    • Status: Resolved
    • Major
    • Resolution: Fixed
    • 4.4
    • 4.5.0-M1
    • KeyValue
    • None

    Description

      When using an non-array constructor of MultiKey, an Object[] is created, which cannot be cast to a K[]

      import org.apache.commons.collections4.keyvalue.MultiKey;
      
      public class MultiKeyClassCastException {
      
          public static void main(String[] args) {
              MultiKeyClassCastException key1 = new MultiKeyClassCastException();
              MultiKeyClassCastException key2 = new MultiKeyClassCastException();
              MultiKeyClassCastException[] keys = new MultiKey<>(key1, key2).getKeys();
          }
      }
      
      // running gives (same error if in module):
      
      Exception in thread "main" java.lang.ClassCastException: class [Ljava.lang.Object; cannot be cast to class [LMultiKeyClassCastException; ([Ljava.lang.Object; is in module java.base of loader 'bootstrap'; [LMultiKeyClassCastException; is in unnamed module of loader 'app')
      	at MultiKeyClassCastException.main(MultiKeyClassCastException.java:8)
      

      AFAIK, the only way to fix this (with source compatibility), is to only have a varargs constructors. but I think this breaks binary compatibility though and cannot be used with the existing constructors.

          @SafeVarargs
          public MultiKey(K... keys) {
              this.keys = keys;
          }
      

      Workaround is to use array constructor with correct typed array or

      Object[] keys = multiKey.getKeys();

      explicitly.

      Attachments

        Activity

          People

            ggregory Gary D. Gregory
            wlaan Walter Laan
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved: