@SuperBuilder 和fastjson序列化问题定位

83 阅读3分钟

背景

为了通过 build 模式为对象赋值,我们会在类上标注@SuperBuilder注解。选择@SuperBuilder而非@Builder,原因在于前者支持父类的 build 模式,而后者不具备这一特性。不过,在使用@SuperBuilder后,却发现其与 fastjson2 存在不兼容的问题。


public interface SignPayload {}

public interface Md5Signer extends SignPayload {}

@ToString
@Setter
@Getter
@Slf4j
@SuperBuilder
public class BaseSignRequest implements Md5Signer {
    private Long timestamp;
    private String sign;
}


@Setter
@Getter
@SuperBuilder
public class TanWanBaseRequest extends BaseSignRequest {
    /**
     * 子游戏id
     */
    @SignField(order = 1)
    private List<Long> subGameIds;
}


TanWanBaseRequest tanWanBaseRequest = JSONObject.parseObject(requestStr, TanWanBaseRequest.class);
com.alibaba.fastjson2.JSONException: invoke constructor error, protected com.wf.game.sdk.hub.core.game.tanwan.req.TanWanBaseRequest(hub.core.game.tanwan.req.TanWanBaseRequest$TanWanBaseRequestBuilder)

	at com.alibaba.fastjson2.reader.ConstructorFunction.apply(ConstructorFunction.java:148)
	at com.alibaba.fastjson2.reader.ConstructorFunction.apply(ConstructorFunction.java:15)
	at com.alibaba.fastjson2.reader.ObjectReaderNoneDefaultConstructor.createInstanceNoneDefaultConstructor(ObjectReaderNoneDefaultConstructor.java:53)
	at com.alibaba.fastjson2.reader.ObjectReaderNoneDefaultConstructor.readObject(ObjectReaderNoneDefaultConstructor.java:291)
	at com.alibaba.fastjson2.JSON.parseObject(JSON.java:600)
	at com.alibaba.fastjson2.JSONObject.parseObject(JSONObject.java:1830)
	at com.wf.game.sdk.api.utils.SignerUtilTest.testTanWan(SignerUtilTest.java:31)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.base/java.lang.reflect.Method.invoke(Method.java:566)
	at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:725)
	at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
	at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
	at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
	at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
	at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
	at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
	at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
	at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
	at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
	at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
	at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
	at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
	at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
	at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$7(TestMethodTestDescriptor.java:214)
	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
	at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:210)
	at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:135)
	at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:66)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:151)
	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
	at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
	at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
	at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
	at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
	at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
	at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
	at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
	at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35)
	at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
	at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54)
	at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:107)
	at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
	at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)
	at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
	at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
	at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:114)
	at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:86)
	at org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:86)
	at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:53)
	at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:57)
	at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38)
	at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11)
	at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35)
	at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:232)
	at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:55)
Caused by: java.lang.reflect.InvocationTargetException
	at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
	at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
	at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
	at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
	at com.alibaba.fastjson2.reader.ConstructorFunction.apply(ConstructorFunction.java:146)
	... 75 more
Caused by: java.lang.NullPointerException
	at hub.core.sign.request.BaseSignRequest$BaseSignRequestBuilder.access$000(BaseSignRequest.java:27)
	at hub.core.sign.request.BaseSignRequest.<init>(BaseSignRequest.java:27)
	at hub.core.game.tanwan.req.TanWanBaseRequest.<init>(TanWanBaseRequest.java:18)
	... 80 more

原因

fastjson2 与Lombok的@SuperBuilder存在兼容性问题,无法找到合适的构造函数进行反序列化

写个示例看下 @Builder@SuperBuilder 区别

@Getter
@Setter
@Builder
public class BaseBuilderRequest {
    private String requestId;
    private Long timestamp;
    private String version;
}

/**
 * 基础请求类,使用@SuperBuilder注解
 * 演示fastjson2与@SuperBuilder的兼容性问题
 */
@Getter
@Setter
@SuperBuilder
public class BaseRequest {
    private String requestId;
    private Long timestamp;
    private String version;
    
    // 默认构造函数被@SuperBuilder隐式禁用
    // 这是导致fastjson2反序列化失败的根本原因
}

编译看下最终生成的类 BaseBuilderRequest 有构造函数

public class BaseBuilderRequest {
    private String requestId;
    private Long timestamp;
    private String version;

    BaseBuilderRequest(String requestId, Long timestamp, String version) {
        this.requestId = requestId;
        this.timestamp = timestamp;
        this.version = version;
    }

    public static BaseBuilderRequestBuilder builder() {
        return new BaseBuilderRequestBuilder();
    }

    public String getRequestId() {
        return this.requestId;
    }

    public Long getTimestamp() {
        return this.timestamp;
    }

    public String getVersion() {
        return this.version;
    }

    public void setRequestId(String requestId) {
        this.requestId = requestId;
    }

    public void setTimestamp(Long timestamp) {
        this.timestamp = timestamp;
    }

    public void setVersion(String version) {
        this.version = version;
    }

    public static class BaseBuilderRequestBuilder {
        private String requestId;
        private Long timestamp;
        private String version;

        BaseBuilderRequestBuilder() {
        }

        public BaseBuilderRequestBuilder requestId(String requestId) {
            this.requestId = requestId;
            return this;
        }

        public BaseBuilderRequestBuilder timestamp(Long timestamp) {
            this.timestamp = timestamp;
            return this;
        }

        public BaseBuilderRequestBuilder version(String version) {
            this.version = version;
            return this;
        }

        public BaseBuilderRequest build() {
            return new BaseBuilderRequest(this.requestId, this.timestamp, this.version);
        }

        public String toString() {
            return "BaseBuilderRequest.BaseBuilderRequestBuilder(requestId=" + this.requestId + ", timestamp=" + this.timestamp + ", version=" + this.version + ")";
        }
    }
}
public class BaseRequest {
    private String requestId;
    private Long timestamp;
    private String version;

    protected BaseRequest(BaseRequestBuilder<?, ?> b) {
        this.requestId = b.requestId;
        this.timestamp = b.timestamp;
        this.version = b.version;
    }

    public static BaseRequestBuilder<?, ?> builder() {
        return new BaseRequestBuilderImpl();
    }

    public String getRequestId() {
        return this.requestId;
    }

    public Long getTimestamp() {
        return this.timestamp;
    }

    public String getVersion() {
        return this.version;
    }

    public void setRequestId(String requestId) {
        this.requestId = requestId;
    }

    public void setTimestamp(Long timestamp) {
        this.timestamp = timestamp;
    }

    public void setVersion(String version) {
        this.version = version;
    }

    private static final class BaseRequestBuilderImpl extends BaseRequestBuilder<BaseRequest, BaseRequestBuilderImpl> {
        private BaseRequestBuilderImpl() {
        }

        protected BaseRequestBuilderImpl self() {
            return this;
        }

        public BaseRequest build() {
            return new BaseRequest(this);
        }
    }

    public abstract static class BaseRequestBuilder<C extends BaseRequest, B extends BaseRequestBuilder<C, B>> {
        private String requestId;
        private Long timestamp;
        private String version;

        public BaseRequestBuilder() {
        }

        protected abstract B self();

        public abstract C build();

        public B requestId(String requestId) {
            this.requestId = requestId;
            return this.self();
        }

        public B timestamp(Long timestamp) {
            this.timestamp = timestamp;
            return this.self();
        }

        public B version(String version) {
            this.version = version;
            return this.self();
        }

        public String toString() {
            return "BaseRequest.BaseRequestBuilder(requestId=" + this.requestId + ", timestamp=" + this.timestamp + ", version=" + this.version + ")";
        }
    }

解决方案

方案一 生成构造函数(推荐)

子类父类标记这种方案简单快捷

@AllArgsConstructor
@NoArgsConstructor

方案二 @JSONCreator

/**
 * 带@JSONCreator注解的构造函数
 * fastjson2会优先使用此构造函数进行反序列化
 */
@JSONCreator
public FixedBaseRequest(
        @JSONField(name = "requestId") String requestId,
        @JSONField(name = "timestamp") Long timestamp,
        @JSONField(name = "version") String version) {
    this.requestId = requestId;
    this.timestamp = timestamp;
    this.version = version;
}

方案三 @Builder

TanWanBaseRequest 移除@SuperBuilder 修改成@Builder BaseSignRequest 移除@SuperBuilder

@Setter
@Getter
//@SuperBuilder 修改成@Builder
@Builder
public class TanWanBaseRequest extends BaseSignRequest {
    /**
     * 子游戏id
     */
    @SignField(order = 1)
    private List<Long> subGameIds;
}
// 移除 @SuperBuilder
@ToString
@Setter
@Getter
@Slf4j
public class BaseSignRequest implements Md5Signer {}

总结

这个兼容性问题的根本原因是设计理念的冲突

  • Lombok的@SuperBuilder专注于Builder模式,移除了传统构造函数
  • FastJson2的反序列化机制依赖传统的对象创建方式

解决方案是在保持Builder模式优势的同时,为JSON反序列化提供必要的构造函数支持。

其他JSON库的兼容性

JSON库兼容性说明
FastJson2需要无参构造函数或@JSONCreator
Jackson更好的Lombok支持
Gson类似问题,需要无参构造函数