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 produce a warning:
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?
The closest I can get is with the help of guard clauses:
Object recordValue = genericRecord.get(someField);
switch (actualValue) {
case String avroString -> {
// do logic
}
case Object o when o instanceof ByteBuffer -> {
var buffer = (ByteBuffer) o;
// do logic
}
default -> log.warn("Unknown type");
}
The compiler will recognize the type check in the guard clause and will not warn you when you cast to a ByteBuffer
.