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 1f130fb271..08ce961d23 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 0000000000..6e385273b5 --- /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)); + } +}