Java annotations small scale

Java annotations manner specified by url must include the key:

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.");
            }
        }
    }
}

 

Run the test (default KEY2 is empty, then throw an exception):

 

Guess you like

Origin www.cnblogs.com/areful/p/11417376.html