zoukankan      html  css  js  c++  java
  • Java注解小试

    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为空,于是抛异常):

  • 相关阅读:
    (转)通过Javascript得到URL中的参数(query string)
    (转)对存储过程进行加密和解密(SQL 2008/SQL 2012)
    (转)怎样玩转千万级别的数据
    (转)mongodb学习(翻译1)
    (转)Web API 强势入门指南
    (转)正则表达式—RegEx(RegularExpressio)(三)
    学习进度-16 python爬虫
    学习进度-15 变量类型的转换
    学习进度-14
    学习进度-13
  • 原文地址:https://www.cnblogs.com/areful/p/11417376.html
Copyright © 2011-2022 走看看