Detailed explanation of spring’s stringutils pit records
cause
Recently, when writing crud, I found that a paging VO has poor robustness. I changed it for a while. Unexpectedly, several functions have problems after the change.
The key codes of the original VO are as follows:
public class PageVo implements Serializable{ // ...省略所有无关代码 Map<String,String> query }
This VO is used to pass parameters during paging query from the front end, and query is used to pass query conditions (whether it is reasonable to pass parameters with map is not discussed here). When there are no query conditions at the current end, the query will be null. If you don't pay attention, NPE is easy to occur.
So I transformed it into the following.
public class PageVo implements Serializable{ // ...省略所有无关代码 Map<String,String> query=new HashMap<> }
But I didn't expect that such a simple transformation would overturn (・ ε ・`)
I had no choice but to check the problem.
discover problems
I've thought about many reasons, but I really didn't think it was because of this (/ ` Д′)/~ ╧╧╧╧╧╧╧╧╧╧╧╧╧╧╧╧╧╧
if (StringUtils.isEmpty(page.getQuery())) { // 省略处理逻辑 }
Actually use stringutils to judge whether a map is empty. At least change a collectionutils
Although predecessors dug holes, why is spring's' stringutils designed to support object input parameters o_ o ....
After thinking about it, I'd better take a look at the source code
Source code analysis
The source code of the isempty () method of stringutils is super simple, and it can be done in three lines of code (in fact, strictly speaking, it is only one line of code):
public static boolean isEmpty(@Nullable Object str) { return (str == null || "".equals(str)); }
Since my map object is not null, the problem should be the equals () method of string. Not much to say, continue to track the source code
public boolean equals(Object anObject) { if (this == anObject) { return true; } // 问题出在这里 if (anObject instanceof String) { String anotherString = (String)anObject; int n = value.length; if (n == anotherString.value.length) { char v1[] = value; char v2[] = anotherString.value; int i = 0; while (n-- != 0) { if (v1[i] != v2[i]) return false; i++; } return true; } } return false; }
The logic of this equals () method is simple
My problem is caused by the second point, because the types are different ┴ - ┴ (` □ ′)
Lesson summary
The above is the whole content of this article. I hope it will help you in your study, and I hope you will support us a lot.