From 686cdfdc871ed323b46761bc5a99d851cc2c4a26 Mon Sep 17 00:00:00 2001 From: chaokunyang Date: Fri, 6 Oct 2023 18:22:26 +0800 Subject: [PATCH] add autocast doc and tests --- java/fury-core/src/main/java/io/fury/Fury.java | 18 +++++++++++++++++- .../src/test/java/io/fury/FuryTest.java | 15 +++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/java/fury-core/src/main/java/io/fury/Fury.java b/java/fury-core/src/main/java/io/fury/Fury.java index 6c3fc0fb33..87b194aaf6 100644 --- a/java/fury-core/src/main/java/io/fury/Fury.java +++ b/java/fury-core/src/main/java/io/fury/Fury.java @@ -618,7 +618,23 @@ public long readLong(MemoryBuffer buffer) { return LongSerializer.readLong(buffer, longEncoding); } - /** Deserialize obj from a byte array. */ + /** + * Deserialize obj from a byte array. Note declared result type must be a class or + * superclass/interface of the serialized object, otherwise a {@link ClassCastException} will be + * thrown. + * + *

For example, if you serialized an object of type `Integer`, then your declared deserialized + * type is `String`, the deserialization will just throw a {@link ClassCastException}. + * + *

{@code
+   * byte[] bytes = fury.serialize(1);
+   * String o = fury.deserialize(bytes); // throw ClassCastException.
+   * }
+ * + * @param bytes serialized data. + * @param result type of the data. + * @return deserialized object. + */ public T deserialize(byte[] bytes) { return deserialize(MemoryUtils.wrap(bytes), null); } diff --git a/java/fury-core/src/test/java/io/fury/FuryTest.java b/java/fury-core/src/test/java/io/fury/FuryTest.java index bcbd90bc72..5f24dd27a6 100644 --- a/java/fury-core/src/test/java/io/fury/FuryTest.java +++ b/java/fury-core/src/test/java/io/fury/FuryTest.java @@ -16,6 +16,7 @@ package io.fury; +import static io.fury.FuryTestBase.getJavaFury; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertThrows; @@ -535,4 +536,18 @@ public void testJavaOutputStream() throws IOException { assertEquals(newObj, beanA); } } + + @Test + public void testDeserializationAutotypeCast() { + Fury fury = getJavaFury(); + byte[] bytes = fury.serialize(1); + Integer i = fury.deserialize(bytes); + Assert.assertEquals(i, 1); + Assert.assertThrows( + ClassCastException.class, + () -> { + String str = fury.deserialize(bytes); + System.out.println(str); + }); + } }