一次简单的自定义注解体

来源:互联网 发布:高性能计算 知乎 编辑:程序博客网 时间:2024/06/06 02:24


很早就听说过自定义注解,自定义JSTL之类  

   为何不动手体验一次简单的自定义注解呢?


  一次简单的自定义注解entity实体验证   ,一个字段的非空验证



先写一个验证非空的注解   (注解长的和接口很像)



package java自定义注解ForSingleField;import java.lang.annotation.Documented;import java.lang.annotation.Inherited;import java.lang.annotation.Retention;import java.lang.annotation.Target;//有时候下面两个包可能不能自动导入,需要复制粘贴导入import java.lang.annotation.RetentionPolicy;import java.lang.annotation.ElementType;/**空指针验证类 * @author TOSHIBA * */@Documented  @Inherited  @Target(ElementType.FIELD)  @Retention(RetentionPolicy.RUNTIME) public @interface IsEmptyAnnotation {public boolean isEmpty() default true;public String message () default "字段不能为空";}


------------------------------------------------------------------------------------------


接下来写一个注解工具,来判断是否符合注解规则






package java自定义注解ForSingleField;import java.lang.reflect.Field;public class AnnotationUtils {/** * @param value   属性值  * @param field   实体field参数 */public void isEmpty(Object value, Field field) {IsEmptyAnnotation annotation = field.getAnnotation(IsEmptyAnnotation.class);if (value == null || value.equals("")) {System.out.println("验证不合格--" +field.getName()+"---"+ annotation.message());} else {System.out.println("验证合格");}}}




---------------------------------------------------------------------------


最后建立一个studen类来验证


package java自定义注解ForSingleField;public class StudentInfo {@IsEmptyAnnotation(message="学生名字不能为空")private String name;public String getName() {return name;}public void setName(String name) {this.name = name;}}



--------------------------------------------------------

main方法测试

先测试字段为空




package java自定义注解ForSingleField;import java.lang.reflect.Field;public class StudentTest {public static void main(String[] args) {StudentInfo studentInfo =new StudentInfo();AnnotationUtils annotationUtils =new AnnotationUtils();Class<? extends StudentInfo> clazz = studentInfo.getClass();Field[] declaredFields = clazz.getDeclaredFields();for (Field field : declaredFields) {annotationUtils.isEmpty(studentInfo.getName(), field);}}}


输出结果为 

验证不合格--name---学生名字不能为空


在给studentInfo.setName("tom");

输出结果为 

验证合格




完结 撒花




原创粉丝点击