修复ObjectUtil.contains处理字符串类型不合理

This commit is contained in:
yanzhongxin 2025-11-25 21:26:08 +08:00
parent 86c3c530b6
commit 820e0d0c8b
2 changed files with 57 additions and 4 deletions

View File

@ -128,7 +128,7 @@ public class ObjectUtil {
* 对象中是否包含元素<br> * 对象中是否包含元素<br>
* 支持的对象类型包括 * 支持的对象类型包括
* <ul> * <ul>
* <li>String</li> * <li>CharSequence</li>
* <li>Collection</li> * <li>Collection</li>
* <li>Map</li> * <li>Map</li>
* <li>Iterator</li> * <li>Iterator</li>
@ -144,11 +144,22 @@ public class ObjectUtil {
if (obj == null) { if (obj == null) {
return false; return false;
} }
if (obj instanceof String) { if (obj instanceof CharSequence) {
if (element == null) { if (!(element instanceof CharSequence)) {
return false; return false;
} }
return ((String) obj).contains(element.toString()); String elementStr;
try {
elementStr = element.toString();
// 检查 toString() 返回 null 的情况
if (elementStr == null) {
return false;
}
} catch (Exception e) {
// 如果toString抛异常认为不包含
return false;
}
return obj.toString().contains(elementStr);
} }
if (obj instanceof Collection) { if (obj instanceof Collection) {
return ((Collection<?>) obj).contains(element); return ((Collection<?>) obj).contains(element);

View File

@ -135,4 +135,46 @@ public class ObjectUtilTest {
// 枚举已经无法使用 // 枚举已经无法使用
assertFalse(enumeration.hasMoreElements()); assertFalse(enumeration.hasMoreElements());
} }
@Test
public void testContainsElementToStringReturnsNull() {
Object problematicElement = new Object() {
@Override
public String toString() {
return null; // 返回 null toString
}
};
assertFalse(ObjectUtil.contains("test", problematicElement)); //不会抛异常
}
@Test
public void testContainsElementToStringInvalidSyntax() {
//字符串包含自定义User对象不符合语义
assertFalse(ObjectUtil.contains("User[id=123]", new User(123)));
}
static class User{
private int id;
public User(int id) {
this.id = id;
}
@Override
public String toString() {
return "User[" +
"id=" + id +
']';
}
}
@Test
public void testContainsCharSequenceSupported() {
//contains方法支持StringStringBuilderStringBuffer
StringBuilder stringBuilder = new StringBuilder("hello world");
StringBuffer stringBuffer = new StringBuffer("hello world");
String str = "hello world";
assertTrue((ObjectUtil.contains(stringBuilder, "world")));
assertTrue(ObjectUtil.contains(stringBuffer, "hello"));
assertTrue(ObjectUtil.contains(str, "hello"));
}
} }