当前位置:网站首页>案例:检查空字段【注解+反射+自定义异常】
案例:检查空字段【注解+反射+自定义异常】
2022-07-06 09:33:00 【小白说(๑• . •๑)】
学习永不止步!
一个结合了注解、反射、自定义异常知识的小案例——检查空字段!
1、定义一个规范类:凡是需要进行字段检查都需要实现
package com.dongzi;
/** * 定义规范化接口 */
public interface CheckRule {
}
2、定义实体类并实现规范接口:需要进行字段检查的需要加上CheckField注解,第3项附代码
package com.dongzi;
/** * 模拟实体类 */
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 = "学生年龄")
private Integer age;
private Integer sex;
@CheckField(message = "学生姓名")
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、定义检查字段注解
package com.dongzi;
import java.lang.annotation.*;
/** * 定义检查字段的注解 * <pre> * @Retention:指定运行时 * @Target:指定注解作用范围 * </pre> */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface CheckField {
/** * 是否开启字段NULL值检查 * @return true 默认返回检查开启字段 */
boolean value() default true;
/** * 字段相关描述 */
String message();
}
4、自定义异常:检查到字段为NULL时抛出
package com.dongzi;
/** * 自定义检查异常 */
public class CheckException extends Exception{
/** * 无特殊实现直接调用父类构造 * @param msg 异常消息 */
public CheckException(String msg){
super(msg);
}
}
5、定义检查字段工具类:检查字段的方法
package com.dongzi;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
/** * 定义异常检查工具类 */
public class CommentUtils {
/** * 检查空字段工具类 * * @param checkRule 需要被检查的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:没引入其他工具类,暂代
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异常处理
}
if (objVal == null || "".equals(objVal)) {
throw new CheckException(checkField.message() + ":为必填项");
}
}
}
}
}
}
6、程序开始
package com.dongzi;
public class Main {
public static void main(String[] args) {
// Student student_1 = new Student(1, 23, 1, "法外狂徒——张三"); // 输出结果:~~~字段不为NULL
Student student_2 = new Student(1, null, 1, "法外狂徒——张三"); // 输出结果:学生年龄:为必填项
try {
CommentUtils.checkNonField(student_2);
System.out.println("~~~字段不为NULL");
} catch (CheckException e) {
e.printStackTrace();
}
}
}
7、两种执行结果
- 传入student_1对象:
- 传入student_2对象:
抛出异常,NULL字段检查完成!可完成一个Bean里面所有非空字段的检查。
附1:项目结构
附2:关于反射执行效率
边栏推荐
- 8086 内存
- redux使用说明
- How to configure hosts when setting up Eureka
- JVM之垃圾回收器上篇
- Full record of ByteDance technology newcomer training: a guide to the new growth of school recruitment
- DS18B20數字溫度計系統設計
- Only learning C can live up to expectations top2 P1 variable
- 一个数10年工作经验的微服务架构老师的简历
- Koa Middleware
- 吴军三部曲见识(五) 拒绝伪工作者
猜你喜欢
Assembly language addressing mode
redux使用说明
MySQL日期函数
How to configure hosts when setting up Eureka
Many papers on ByteDance have been selected into CVPR 2021, and the selected dry goods are here
Shell_ 05_ operator
亮相Google I/O,字节跳动是这样应用Flutter的
ByteDance overseas technical team won the championship again: HD video coding has won the first place in 17 items
Shell_ 01_ data processing
[graduation project] QT from introduction to practice: realize imitation of QQ communication, which is also the last blog post in school.
随机推荐
这群程序员中的「广告狂人」,把抖音广告做成了AR游戏
Fdog series (V): use QT to imitate QQ to realize login interface to main interface, function chapter.
DS18B20數字溫度計系統設計
Flink 解析(一):基础概念解析
关于Stream和Map的巧用
Activiti目录(五)驳回、重新发起、取消流程
字节跳动春招攻略:学长学姐笔经面经,还有出题人「锦囊」
Shell_ 04_ Shell script
Flink 解析(二):反压机制解析
ByteDance open source Gan model compression framework, saving up to 97.8% of computing power - iccv 2021
Resume of a microservice architecture teacher with 10 years of work experience
Which is more important for programming, practice or theory [there are some things recently, I don't have time to write an article, so I'll post an article on hydrology, and I'll fill in later]
一个数10年工作经验的微服务架构老师的简历
Yum install XXX reports an error
Fdog series (4): use the QT framework to imitate QQ to realize the login interface, interface chapter.
Alibaba cloud server docker installation mysql5.5
Go language uses the thrift protocol to realize the client and service end reports not enough arguments in call to oprot Writemessagebegin error resolution
The daemon thread starts redis and modifies the configuration file
mysql的合计/统计函数
姚班智班齐上阵,竞赛高手聚一堂,这是什么神仙编程大赛?