1.项目结构如下
2.YangNotNull
package cn.yang37.annotation.p20210425;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @Description: 自定义注解 实现非空判断
* @Author: Yiang37
* @Date: 2021/04/25 21:45:45
* @Version: 1.0
*/@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface YangNotNull {
String value();
}
3.YangNotNullExplain
package cn.yang37.annotation.p20210425;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
/**
* @Description:
* @Class: YangNotNullExplain
* @Author: Yiang37
* @Date: 2021/4/25 21:47
* @Version: 1.0
*/
public class YangNotNullExplain {
public static <T> List<String> validate(T t) throws IllegalAccessException {
ArrayList<String> resList = new ArrayList<>();
//获取类中声明的Field
Field[] declaredFields = t.getClass().getDeclaredFields();
for (Field declaredField : declaredFields) {
// 判断YangNotNull类型注解是否在declaredField类型上
if (declaredField.isAnnotationPresent(YangNotNull.class)) {
// 反射获取的字段值 设置不检查访问权限
declaredField.setAccessible(true);
Object value = declaredField.get(t);
if (value == null) {
YangNotNull yangNotNull = declaredField.getAnnotation(YangNotNull.class);
resList.add(yangNotNull.value() + "不能为空!");
}
}
}
return resList;
}
}
4.User
package cn.yang37.annotation.p20210425;
/**
* @Description:
* @Class: User
* @Author: Yiang37
* @Date: 2021/4/25 21:56
* @Version: 1.0
*/
public class User {
@YangNotNull("inputUsername")
private String username;
@YangNotNull("inputAge")
private int age;
@YangNotNull("inputSex")
private String sex;
}
5.UserTest
package cn.yang37.annotation.p20210425;
import java.util.List;
/**
* @Description:
* @Class: UserTest
* @Author: Yiang37
* @Date: 2021/4/25 21:59
* @Version: 1.0
*/
public class UserTest {
public static void main(String[] args) throws IllegalAccessException {
User user = new User();
List<String> validateList = YangNotNullExplain.validate(user);
validateList.forEach(System.out::println);
}
}
结果
inputUsername不能为空!
inputSex不能为空!