测试 equals 方法与不同引用对象比较失败

This commit is contained in:
zongze.lee 2025-11-06 03:43:41 +08:00
parent 56ffa92e5e
commit ebba917222
2 changed files with 33 additions and 1 deletions

View File

@ -52,7 +52,8 @@ public class PhantomObj<T> extends PhantomReference<T> implements Ref<T>{
if (other == this) { if (other == this) {
return true; return true;
} else if (other instanceof PhantomObj) { } else if (other instanceof PhantomObj) {
return ObjUtil.equals(((PhantomObj<?>) other).get(), get()); // 比较原始对象的哈希码因为虚引用无法获取原始对象
return this.hashCode == ((PhantomObj<?>)other).hashCode;
} }
return false; return false;
} }

View File

@ -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<String> queue;
private String testObject;
private PhantomObj<String> phantomObj;
@BeforeEach
void setUp() {
queue = new ReferenceQueue<>();
testObject = "test";
phantomObj = new PhantomObj<>(testObject, queue);
}
@Test
@DisplayName("测试 equals 方法与不同引用对象比较")
void testEqualsWithDifferentReferent() {
String differentObject = "different";
PhantomObj<String> anotherPhantomObj = new PhantomObj<>(differentObject, queue);
assertFalse(phantomObj.equals(anotherPhantomObj));
}
}