alibaba / alibaba/fastjson2

[BUG] 在自定义Classloader内使用super提供的fastjson,无法正常序列化/反序列化自己loader内加载的类的成员变量

Open
#1,721 0 comments 0 reactions 0 assignees View on GitHub
bug
Dominant language
Java
Stars
4.4k
Forks
611
Avg merge
1d 22h
Merged PRs (30d)
6

Description

### 问题描述
在自定义classloader使用super提供的fastjson来加载本loader加载的类时,无法加载类内同属于本loader加载的类的成员变量

### 环境信息
*请填写以下信息:*

- OS信息: Windows Server 2019
- JDK信息: Openjdk 17
- 版本信息:Fastjson2 2.0.38

### 重现步骤
工程pom.xml如下
```

com.alibaba.fastjson2
fastjson2
2.0.38
provided

```

工程内有两个类,均在自定义的Classloader(CustomLoader)内加载
```
class A {
private int x;

public void setX(int x) { this.x = x;}
public int getX() { return x;}
}

class B {
private A a;

public void setA(A a) {this.a = a;}
public A getA() { return a;}
}

// 此处的JSON是在CustomLoader的super内加载的
JSON,parseObject("{\"a\":{\"x\":1}", B.class);
```

### 期待的正确结果
无报错

### 相关日志输出
```
Caused by: java.lang.NoClassDefFoundError: test/A
at com.alibaba.fastjson2.reader.ORG_12_20_B.readObject(Unknown Source) ~[?:?]
at com.alibaba.fastjson2.JSON.parseObject(JSON.java:726) ~[test.jar:?]
at logic.GameMainLogic.initialize(GameMainLogic.java:59) ~[?:?]
at base.logic.GameLogic.initialize(GameLogic.java:117) ~[?:?]
... 17 more
Caused by: java.lang.ClassNotFoundException: test.A
at com.alibaba.fastjson2.reader.ORG_12_20_B.readObject(Unknown Source) ~[?:?]
at com.alibaba.fastjson2.JSON.parseObject(JSON.java:726) ~[test.jar:?]
```

### 附加信息
该问题在2.0.20版本上不出现,在2.0.21版本上开始存在
初步定位在 ObjectReaderCreatorASM.java
```
public static ObjectReaderCreatorASM INSTANCE = new ObjectReaderCreatorASM(DynamicClassLoader.getInstance());
```

该处的 DynamicClassLoader.getInstance() 在super的ClassLoader加载,因此无法访问该示例的ClassLoader内加载的代码

Contributor guide

Open the contributing guide

Research direction

Start with ObjectReaderCreatorASM.java and the DynamicClassLoader.getInstance() initialization mentioned in the report. Reproduce the issue using custom-loaded classes A and B with fastjson2 2.0.38, comparing behavior with 2.0.20 and 2.0.21. Done means JSON serialization and deserialization can resolve member types loaded by the custom ClassLoader without NoClassDefFoundError.

Written by the indexing model from the issue text.

Assessment

Tech stack
java
Domain
backend
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.