背景
日常開發中,我們通常會根據前端傳過來的實體類的屬性個數去做邏輯判斷,下面的是判斷屬性個數的工具類。
工具類
public static Integer nonNullFieldCount(Req req) {if (req == null) {return 0;}int nonNullFieldCount = 0;Field[] fields = req.getClass().getDeclaredFields();for (Field field : fields) {field.setAccessible(true); // 允許訪問私有屬性try {if (field.get(req) != null) {nonNullFieldCount++;}} catch (IllegalAccessException e) {e.printStackTrace();}}return nonNullFieldCount;}class Req {private String name;private int age;// get set....}
總結
上述是統計前端傳過來的Req的非空屬性個數的工具類,希望能夠幫到你。