如何使用Stream编写校验所有JComponent组件全部非空的通用方法
需求说明
需要对JTextField、JPasswordField、JComboBox、DatePicker四类Swing组件做统一非空校验,要求将原有硬编码参数的实现,改造为入参为组件列表、全Stream逻辑的通用校验方法。
原有实现代码
boolean test(JTextField a, JPasswordField b, DatePicker c, JComboBox<Integer> d) throws Exception { ArrayList<String> text = new ArrayList<>(); if(a==null || b==null || c==null || d==null) throw new Exception(); text.add(a.getText()); text.add(new String(b.getPassword())); String strDate = ""; if (c.getDate()!= null) strDate = c.getDate().format(DateTimeFormatter.ofPattern("dd/MM/yyyy")); text.add(strDate); String strMese = ""; if (d.getSelectedItem() != null) strMese = d.getSelectedItem().toString(); text.add(strMese); return text.stream().noneMatch(String::isEmpty); }
通用Stream实现方案
核心逻辑是在Stream流中完成「组件非空校验→按类型适配取值→转换为字符串→全局空值判断」全流程,和原有逻辑完全对齐:
import java.time.format.DateTimeFormatter; import java.util.List; import javax.swing.JComboBox; import javax.swing.JPasswordField; import javax.swing.JTextField; // 替换为你实际使用的DatePicker全限定名 import org.jdesktop.swingx.JXDatePicker; boolean test(List<?> components) throws Exception { DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("dd/MM/yyyy"); return components.stream() // 校验组件本身不能为null,和原有逻辑一致 .peek(component -> { if (component == null) throw new Exception("校验组件不能为null"); }) // 按组件类型适配取值,转换为对应字符串 .map(component -> { if (component instanceof JTextField tf) { return tf.getText(); } else if (component instanceof JPasswordField pf) { return new String(pf.getPassword()); } else if (component instanceof JXDatePicker dp) { // 如果你用的DatePicker的getDate()直接返回LocalDate,直接简化为return dp.getDate() == null ? "" : dp.getDate().format(DATE_FORMATTER); return dp.getDate() == null ? "" : dp.getDate().toInstant().atZone(java.time.ZoneId.systemDefault()).toLocalDate().format(DATE_FORMATTER); } else if (component instanceof JComboBox<?> cb) { return cb.getSelectedItem() == null ? "" : cb.getSelectedItem().toString(); } else { throw new IllegalArgumentException("不支持的组件类型:" + component.getClass().getName()); } }) // 所有组件取值都不为空才返回true,和原有逻辑一致 .noneMatch(String::isEmpty); }
调用示例
// 把需要校验的组件按任意顺序放入列表即可 List<?> components = List.of( yourTextField, yourPasswordField, yourDatePicker, yourComboBox ); // 校验通过返回true,存在空值返回false,组件为null直接抛出异常 boolean isAllNotEmpty = test(components);
内容的提问来源于stack exchange,提问作者user192837
相关产品推荐
相关产品推荐

