当前位置:网站首页>Case: check the empty field [annotation + reflection + custom exception]
Case: check the empty field [annotation + reflection + custom exception]
2022-07-06 17:18:00 【Xiaobai said (๑• ๑)】
Learning never stops !
A combination of annotations 、 Reflection 、 Small cases of custom exception knowledge —— Check for empty fields !
1、 Define a specification class : All fields that need to be checked need to be implemented
package com.dongzi;
/** * Define standardized interfaces */
public interface CheckRule {
}
2、 Define entity classes and implement standard interfaces : Add CheckField annotation , The first 3 Item with code
package com.dongzi;
/** * Simulate entity class */
public class Student implements CheckRule {
public Student() {
}
public Student(Integer id, Integer age, Integer sex, String name) {
this.id = id;
this.age = age;
this.sex = sex;
this.name = name;
}
private Integer id;
@CheckField(message = " Student age ")
private Integer age;
private Integer sex;
@CheckField(message = " The student's name ")
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getSex() {
return sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
3、 Define check field annotations
package com.dongzi;
import java.lang.annotation.*;
/** * Define the annotation of the check field * <pre> * @Retention: Specify the runtime * @Target: Specify the scope of the annotation * </pre> */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface CheckField {
/** * Whether to open the field NULL Value check * @return true The default return check on field */
boolean value() default true;
/** * Field related description */
String message();
}
4、 Custom exception : Check that the field is NULL Throw when
package com.dongzi;
/** * Custom check exception */
public class CheckException extends Exception{
/** * There is no special implementation to directly call the parent class construction * @param msg Exception message */
public CheckException(String msg){
super(msg);
}
}
5、 Define the check field tool class : How to check fields
package com.dongzi;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
/** * Define exception checking tool classes */
public class CommentUtils {
/** * Check the empty field tool class * * @param checkRule Need to be checked bean */
public static void checkNonField(CheckRule checkRule) throws CheckException {
Class<? extends CheckRule> beanClass = checkRule.getClass();
Field[] fields = beanClass.getDeclaredFields();
if (fields.length > 0) {
for (Field field : fields) {
CheckField checkField = field.getAnnotation(CheckField.class);
if (checkField != null && checkField.value()) {
// field.setAccessible(true);
String fieldName = field.getName();
// TODO: No other tool classes have been introduced , temporarily replace
char[] chars = fieldName.toCharArray();
chars[0] = Character.toUpperCase(chars[0]);
fieldName = String.copyValueOf(chars);
String methodName = "get" + fieldName;
Object objVal;
try {
objVal = beanClass.getMethod(methodName).invoke(checkRule);
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
// method invoke exception handling
}
if (objVal == null || "".equals(objVal)) {
throw new CheckException(checkField.message() + ": Is required ");
}
}
}
}
}
}
6、 Program starts
package com.dongzi;
public class Main {
public static void main(String[] args) {
// Student student_1 = new Student(1, 23, 1, " Outlaw maniac —— Zhang San "); // Output results :~~~ Field is not NULL
Student student_2 = new Student(1, null, 1, " Outlaw maniac —— Zhang San "); // Output results : Student age : Is required
try {
CommentUtils.checkNonField(student_2);
System.out.println("~~~ Field is not NULL");
} catch (CheckException e) {
e.printStackTrace();
}
}
}
7、 Two execution results
- Pass in student_1 object :

- Pass in student_2 object :

Throw an exception ,NULL Field check complete ! Can complete a Bean Check all non empty fields .
attach 1: Project structure

attach 2: About reflection execution efficiency
边栏推荐
- PostgreSQL 14.2, 13.6, 12.10, 11.15 and 10.20 releases
- Only learning C can live up to expectations top5 S1E8 | S1E9: characters and strings & arithmetic operators
- 信息与网络安全期末复习(基于老师给的重点)
- JVM 垃圾回收器之Serial SerialOld ParNew
- Activiti目录(三)部署流程、发起流程
- Assembly language addressing mode
- Flink源码解读(一):StreamGraph源码解读
- Only learning C can live up to expectations top3 demo exercise
- Von Neumann architecture
- 吴军三部曲见识(四) 大家智慧
猜你喜欢

吴军三部曲见识(五) 拒绝伪工作者

koa中间件

Wu Jun's trilogy experience (VII) the essence of Commerce

Introduction to spring trick of ByteDance: senior students, senior students, senior students, and the author "brocade bag"

JVM garbage collector part 2

Flink 解析(七):时间窗口

JVM 垃圾回收器之Garbage First

原型链继承

Yao BanZhi and his team came together, and the competition experts gathered together. What fairy programming competition is this?

服务器端渲染(SSR)和客户端渲染(CSR)的区别
随机推荐
Flink源码解读(二):JobGraph源码解读
GCC error: terminate called after throwing an instance of 'std:: regex_ error‘ what(): regex
JVM 垃圾回收器之Serial SerialOld ParNew
Login to verify the simple use of KOA passport Middleware
【逆向中级】跃跃欲试
微信防撤回是怎么实现的?
Ce n'est qu'en apprenant que c est à la hauteur des attentes Top5 s1e8 | s1e9: caractères et chaînes & opérateurs arithmétiques
算数运算指令
面试集锦库
Only learning C can live up to expectations Top1 environment configuration
Only learning C can live up to expectations top2 P1 variable
JVM garbage collector part 2
8086 CPU 内部结构
1. Introduction to JVM
吴军三部曲见识(四) 大家智慧
关于Stream和Map的巧用
Flink 解析(五):State与State Backend
MySQL数字函数
案例:检查空字段【注解+反射+自定义异常】
MySQL digital function