Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[BUG] record类型无法正确识别泛型 #3156

Open
authorZhao opened this issue Nov 11, 2024 · 0 comments
Open

[BUG] record类型无法正确识别泛型 #3156

authorZhao opened this issue Nov 11, 2024 · 0 comments
Labels
bug Something isn't working

Comments

@authorZhao
Copy link

问题描述

record类型无法正确识别泛型。

环境信息

请填写以下信息:

  • OS信息: [e.g.:win11 i7 12Core 3.10GHz 32GB]
  • JDK信息: oracle jdk 21
  • 版本信息:[e.g.:Fastjson2 3.5.3]

重现步骤

如何操作可以重现该问题:

  1. 使用 xxx.xxx 方法
  2. 输入 ... 数据
  3. 出现 ... 错误
public record AjaxResult<T>(int code, String msg, T data)  {}

//public class AjaxResult<T> {
//    private int code;
//    private String msg;
//    private T data;
//
//    public AjaxResult() {
//    }
//
//    public int getCode() {
//        return code;
//    }
//
//    public AjaxResult<T> setCode(int code) {
//        this.code = code;
//        return this;
//    }
//
//    public String getMsg() {
//        return msg;
//    }
//
//    public AjaxResult<T> setMsg(String msg) {
//        this.msg = msg;
//        return this;
//    }
//
//    public T getData() {
//        return data;
//    }
//
//    public AjaxResult<T> setData(T data) {
//        this.data = data;
//        return this;
//    }
//}
public class LoginResult {
    private Long userId;
    private String name;
}
public class TestJsonRecord {
    static String json = """
        {
             "code": 200,
             "data": {
                 "userId": 1524231,
                 "name": "张三"
             }
         }
        """;

    public static void main(String[] args) {
        AjaxResult<LoginResult> loginResultAjaxResult = JSON.parseObject(json, new TypeReference<AjaxResult<LoginResult>>() {
        });
        System.out.println("loginResultAjaxResult = " + loginResultAjaxResult.data().getClass().getName());
    }
}

期待的正确结果

输出loginResultAjaxResult 里面data字段的类型,

如果是使用record就会报错,如果使用注释的用法就会正常输出类名,使用record,里面的泛型信息丢失,被反序列化JsonObject

相关日志输出

Exception in thread "main" java.lang.ClassCastException: class com.alibaba.fastjson2.JSONObject cannot be cast to class LoginResult (com.alibaba.fastjson2.JSONObject and LoginResult are in unnamed module of loader 'app')
at TestJsonRecord.main(TestJsonRecord.java:24)

附加信息

bcfc173c-0957-4b49-9e17-297ac540392e

@authorZhao authorZhao added the bug Something isn't working label Nov 11, 2024
@authorZhao authorZhao changed the title [BUG] [BUG] record类型无法正确识别泛型 Nov 11, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

1 participant