From 940022f52afe26844d84ebd4d379c4842b63d863 Mon Sep 17 00:00:00 2001 From: Sergey Shanshin Date: Tue, 13 Jun 2023 16:37:25 +0300 Subject: [PATCH] Fixed NoSuchMethodError when parsing a JSON stream on Java 8 (#2328) Fixes #2326 An explicit cast is needed here due to an API change in Java 9, see #2218. In Java 8 and earlier, the `position(I)` method was final in `Buffer`, and returned a `Buffer`. In Java 9 and later, the method was opened, and `ByteBuffer` overrides it, returning a `ByteBuffer`. This causes a `NoSuchMethodError` when running a class, compiled with a newer Java version, on Java 8. --- .../src/kotlinx/serialization/json/internal/CharsetReader.kt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/formats/json/jvmMain/src/kotlinx/serialization/json/internal/CharsetReader.kt b/formats/json/jvmMain/src/kotlinx/serialization/json/internal/CharsetReader.kt index 61fc79109..d7c606bd9 100644 --- a/formats/json/jvmMain/src/kotlinx/serialization/json/internal/CharsetReader.kt +++ b/formats/json/jvmMain/src/kotlinx/serialization/json/internal/CharsetReader.kt @@ -103,7 +103,8 @@ internal class CharsetReader( val remaining = if (position <= limit) limit - position else 0 val bytesRead = inputStream.read(byteBuffer.array(), byteBuffer.arrayOffset() + position, remaining) if (bytesRead < 0) return bytesRead - byteBuffer.position(position + bytesRead) + // Method `position(I)LByteBuffer` does not exist in Java 8. For details, see comment for `flip` in `init` method + (byteBuffer as Buffer).position(position + bytesRead) } finally { (byteBuffer as Buffer).flip() // see the `init` block in this class for the reasoning behind the cast }