Java 注解实现字段长度校验 - 自定义注解 LengthCheck
可以使用以下代码实现:
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface LengthCheck {
int maxLength() default 10;
}
上述代码定义了一个注解类LengthCheck,其中@Target(ElementType.FIELD)表示该注解可以用于字段上,@Retention(RetentionPolicy.RUNTIME)表示该注解在运行时可通过反射获取,@Inherited表示该注解可以被子类继承。
接下来,可以编写一个测试类来验证该注解的使用:
public class AnnotationTest {
@LengthCheck(maxLength = 10)
private String name;
public static void main(String[] args) {
AnnotationTest test = new AnnotationTest();
test.setName("Hello, World!");
Class<?> clazz = test.getClass();
try {
java.lang.reflect.Field field = clazz.getDeclaredField("name");
LengthCheck annotation = field.getAnnotation(LengthCheck.class);
if (annotation != null) {
int maxLength = annotation.maxLength();
String value = (String) field.get(test);
if (value.length() > maxLength) {
System.out.println("Field length exceeds the maximum allowed length of " + maxLength);
} else {
System.out.println("Field length is within the allowed limit");
}
} else {
System.out.println("Annotation not found");
}
} catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}
}
public void setName(String name) {
this.name = name;
}
}
上述代码中,首先定义了一个带有@LengthCheck注解的私有字段name。在main方法中,通过反射获取name字段上的@LengthCheck注解,并获取注解中的maxLength值。然后,通过反射获取name字段的值,并判断其长度是否超过了maxLength,如果超过则输出相应的提示信息。最后,调用setName方法为name字段赋值。
运行该测试类,可以看到输出结果为:
Field length exceeds the maximum allowed length of 10
这说明name字段的长度超过了允许的最大长度。
原文地址: https://www.cveoy.top/t/topic/qd9d 著作权归作者所有。请勿转载和采集!