javaavro

Enhanced switch for non-public classes


Occasionally a 3rd party library contains APIs that return non-public classes which you cannot reference directly. One such example is org.apache.avro.generic.GenericRecord.get() which can sometimes return a java.nio.HeapByteBuffer object. If I wanted to switch over that class like so I will get a compile error:

Object recordValue = genericRecord.get(someField);
switch (actualValue) {
   case String avroString -> {
      // do logic
   }
   case HeapByteBuffer avroBuffer -> {
      // do logic
   }
   default -> log.warn("Unknown type");
}

If instead I try to use an extending class, the code will compile but will log the warning message "Unknown type":

Object recordValue = genericRecord.get(someField);
switch (actualValue) {
   case String avroString -> {
      // do logic
   }
   case ByteBuffer avroBuffer -> {
      // do logic
   }
   default -> log.warn("Unknown type");
}

How can I use an enhanced switch for a private class?


Solution

  • The second example in my orignal answer works fine. Not sure what I did to hit the log.warn() before:

    Object recordValue = genericRecord.get(someField);
    switch (actualValue) {
       case String avroString -> {
          // do logic
       }
       case ByteBuffer avroBuffer -> {
          // do logic
       }
       default -> log.warn("Unknown type");
    }