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