From 538ad85124ef9b1bc2edf24a5fe8a91c2dc9ef05 Mon Sep 17 00:00:00 2001 From: ZhouXY108 Date: Sat, 12 Oct 2024 00:22:02 +0800 Subject: [PATCH] =?UTF-8?q?=E6=94=B9=E8=BF=9B=20ValidatableStringRecord?= =?UTF-8?q?=EF=BC=8C=E5=AD=90=E7=B1=BB=E5=8F=AF=E4=BB=A5=E8=8E=B7=E5=8F=96?= =?UTF-8?q?=20matcher=20=E5=81=9A=E6=9B=B4=E5=A4=9A=E6=93=8D=E4=BD=9C?= =?UTF-8?q?=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../model/ValidatableStringRecord.java | 33 +++++++++++++++---- 1 file changed, 27 insertions(+), 6 deletions(-) diff --git a/src/main/java/xyz/zhouxy/plusone/commons/model/ValidatableStringRecord.java b/src/main/java/xyz/zhouxy/plusone/commons/model/ValidatableStringRecord.java index fc99bd7..c4d42c3 100644 --- a/src/main/java/xyz/zhouxy/plusone/commons/model/ValidatableStringRecord.java +++ b/src/main/java/xyz/zhouxy/plusone/commons/model/ValidatableStringRecord.java @@ -18,11 +18,13 @@ package xyz.zhouxy.plusone.commons.model; import java.io.Serializable; import java.util.Objects; +import java.util.function.Supplier; +import java.util.regex.Matcher; import java.util.regex.Pattern; -import com.google.common.base.Preconditions; +import javax.annotation.Nonnull; -import xyz.zhouxy.plusone.commons.util.RegexTools; +import xyz.zhouxy.plusone.commons.util.AssertTools; /** * 带校验的字符串值对象 @@ -32,12 +34,27 @@ import xyz.zhouxy.plusone.commons.util.RegexTools; */ public abstract class ValidatableStringRecord implements Comparable, Serializable { + + @Nonnull private final String value; - protected ValidatableStringRecord(String value, Pattern pattern) { - Preconditions.checkNotNull(pattern, "The pattern must not be null."); - Preconditions.checkNotNull(value, "The value must not be null."); - Preconditions.checkArgument(RegexTools.matches(value, pattern)); + private final transient Matcher matcher; + + protected ValidatableStringRecord(@Nonnull String value, @Nonnull Pattern pattern) { + this(value, pattern, "Invalid value"); + } + + protected ValidatableStringRecord(@Nonnull String value, @Nonnull Pattern pattern, + @Nonnull Supplier errorMessageSupplier) { + this(value, pattern, errorMessageSupplier.get()); + } + + protected ValidatableStringRecord(@Nonnull String value, @Nonnull Pattern pattern, + @Nonnull String errorMessage) { + AssertTools.checkArgumentNotNull(value, "The value cannot be null."); + AssertTools.checkArgumentNotNull(pattern, "The pattern cannot be null."); + this.matcher = pattern.matcher(value); + AssertTools.checkArgument(this.matcher.matches(), errorMessage); this.value = value; } @@ -77,5 +94,9 @@ public abstract class ValidatableStringRecord return this.value(); } + protected final Matcher getMatcher() { + return matcher; + } + private static final long serialVersionUID = -8365241662025469652L; }