定義註解並使用

如何定義並使用java註解

本文來自對codesheep的總結
1. 創建@interface註解,定義字段
2. 在要使用的地方實現validate方法,假如我就在Student類下進行驗證,代碼如下:

先曬工程目錄:
工程目錄

  1. 定義註解
package annotationTest;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Length {

    int min();

    int max();

    String errorMsg();

}
  1. 實現驗證
package annotationTest;

import java.lang.reflect.Field;

public class Student {

    @Length(min = 11, max = 11, errorMsg = "Error! the length must be 11 bits")
    private String mobile;

    public String validate(Object object) throws IllegalAccessException {

        Field[] fields = object.getClass().getDeclaredFields();
        System.out.println("fields lenght:" + fields.length);
        
        for (Field field : fields) {
            if (field.isAnnotationPresent(Length.class)) {
                Length length = field.getAnnotation(Length.class);
                field.setAccessible(true);

                int value = ((String) field.get(object)).length();
                System.out.println("min:" + length.min());
                if (value < length.min() || value > length.max())
                    return length.errorMsg();
            }

        }

        return "correct";
    }

    public static void main(String[] args) {
        Student s = new Student();
        // 設置一個不是11位數的錯誤值進行驗證
        s.mobile = "123";
        String ret;
        try {
            ret = s.validate(s);
            //打印出驗證的結果
            System.out.println(ret);
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

輸出結果:
按F8調試輸出結果

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章