From ebba91722272295347bfc39fd813da416c41cfed Mon Sep 17 00:00:00 2001 From: "zongze.lee" Date: Thu, 6 Nov 2025 03:43:41 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B5=8B=E8=AF=95=20equals=20=E6=96=B9?= =?UTF-8?q?=E6=B3=95=E4=B8=8E=E4=B8=8D=E5=90=8C=E5=BC=95=E7=94=A8=E5=AF=B9?= =?UTF-8?q?=E8=B1=A1=E6=AF=94=E8=BE=83=E5=A4=B1=E8=B4=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../hutool/v7/core/lang/ref/PhantomObj.java | 3 +- .../v7/core/lang/ref/PhantomObjTest.java | 31 +++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 hutool-core/src/test/java/cn/hutool/v7/core/lang/ref/PhantomObjTest.java diff --git a/hutool-core/src/main/java/cn/hutool/v7/core/lang/ref/PhantomObj.java b/hutool-core/src/main/java/cn/hutool/v7/core/lang/ref/PhantomObj.java index 1f130fb27..08ce961d2 100644 --- a/hutool-core/src/main/java/cn/hutool/v7/core/lang/ref/PhantomObj.java +++ b/hutool-core/src/main/java/cn/hutool/v7/core/lang/ref/PhantomObj.java @@ -52,7 +52,8 @@ public class PhantomObj extends PhantomReference implements Ref{ if (other == this) { return true; } else if (other instanceof PhantomObj) { - return ObjUtil.equals(((PhantomObj) other).get(), get()); + // 比较原始对象的哈希码,因为虚引用无法获取原始对象 + return this.hashCode == ((PhantomObj)other).hashCode; } return false; } diff --git a/hutool-core/src/test/java/cn/hutool/v7/core/lang/ref/PhantomObjTest.java b/hutool-core/src/test/java/cn/hutool/v7/core/lang/ref/PhantomObjTest.java new file mode 100644 index 000000000..6e385273b --- /dev/null +++ b/hutool-core/src/test/java/cn/hutool/v7/core/lang/ref/PhantomObjTest.java @@ -0,0 +1,31 @@ +package cn.hutool.v7.core.lang.ref; + +import java.lang.ref.ReferenceQueue; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class PhantomObjTest { + + private ReferenceQueue queue; + private String testObject; + private PhantomObj phantomObj; + + @BeforeEach + void setUp() { + queue = new ReferenceQueue<>(); + testObject = "test"; + phantomObj = new PhantomObj<>(testObject, queue); + } + + @Test + @DisplayName("测试 equals 方法与不同引用对象比较") + void testEqualsWithDifferentReferent() { + String differentObject = "different"; + PhantomObj anotherPhantomObj = new PhantomObj<>(differentObject, queue); + assertFalse(phantomObj.equals(anotherPhantomObj)); + } +}