Java 17 Module System Strengthening Causes Gson Serialization Error, Resolved with Custom TypeAdapter
Key point
Java 17's strong encapsulation policy blocked Gson's reflection access, and the issue was resolved using a Custom TypeAdapter.
Details
A Kurly developer encountered a Gson serialization error while upgrading from Spring Boot 2.5.3 to 3.2.4, and from Java 11 to 17. An InaccessibleObjectException occurred when storing a LocalDateTime object in Redis during login, caused by the strong encapsulation policy applied from Java 17 onward, which blocks reflection-based access to internal fields within the java.time package.
Changes in the Java Module System
The module system introduced in Java 9 initially allowed reflection access for backward compatibility, but restrictions were gradually strengthened.
- Java 9:
--illegal-access=permitset as default, allowing reflective access to internal JDK elements - Java 16: Default changed to
--illegal-access=deny, blocking access to internal packages by default - Java 17: JEP 403 applied, strictly restricting internal API access via
setAccessible(true), with no single option to relax it
As a result, Gson's default behavior via ReflectiveTypeAdapterFactory could no longer access private final fields.
Resolution via Custom TypeAdapter
The Gson project finds it difficult to fundamentally resolve the issue of serializing platform package objects. Therefore, instead of changing field visibility, the developer worked around the problem by writing a Custom TypeAdapter.
- Implemented by extending
TypeAdapter<LocalDateTime> - Performed serialization and deserialization manually using
DateTimeFormatter.ISO_LOCAL_DATE_TIME - When a custom adapter is registered, it takes priority over Gson's reflection-based factory, allowing the access restriction to be bypassed
Through this approach, the developer removed the dependency on reflection and secured normal serialization behavior while maintaining security.
This summary was generated automatically by AI. Check the original for the author's claims and context. Copyright belongs to the original author.
Our guide explains how the AI works. Report summary errors, attribution issues, or removal requests via Contact.