码迷,mamicode.com
首页 > 编程语言 > 详细

Java注解小试

时间:2019-08-27 12:28:00      阅读:88      评论:0      收藏:0      [点我收藏+]

标签:required   ref   color   void   测试   def   key   final   rgs   

Java通过注解方式指明url中必须包括键值:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class AnnotationTest {
    @Target(ElementType.FIELD)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface CbdLinkAnnotation {
        enum TYPE {OPTIONAL, REQUIRED}

        TYPE value() default TYPE.OPTIONAL;
    }

    public static class A {
        @CbdLinkAnnotation(value = CbdLinkAnnotation.TYPE.OPTIONAL)
        public static final String KEY1 = "key1";
        @CbdLinkAnnotation(value = CbdLinkAnnotation.TYPE.REQUIRED)
        public static final String KEY2 = "key2";

        public Map<String, String> map = new HashMap<>();

        public A(String url) {
            //TODO: convert String to Map<String, String>
        }
    }

    public static void main(String[] args) {
        Set<String> set = new HashSet<>();
        Field[] fields = A.class.getFields();
        for (Field field : fields) {
            CbdLinkAnnotation[] annotations = field.getAnnotationsByType(CbdLinkAnnotation.class);
            if (annotations != null) {
                for (CbdLinkAnnotation annotation : annotations) {
                    if (annotation.value() == CbdLinkAnnotation.TYPE.REQUIRED) {
                        set.add(field.getName());
                    }
                }
            }
        }

        A a = new A("your_custom_string?key1=value1&key2=value2");
        for (String s : set) {
            if (!a.map.containsKey(s)) {
                throw new RuntimeException("key " + s + " is required.");
            }
        }
    }
}

 

运行测试(默认KEY2为空,于是抛异常):

技术图片

 

Java注解小试

标签:required   ref   color   void   测试   def   key   final   rgs   

原文地址:https://www.cnblogs.com/areful/p/11417376.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!