Java annotations demo

# In order to become familiar with the notes, write a small demo
main function is to scan # demo of a class contains our custom method annotations, and then put them into a map of the return value

public class QQ {

    public static void main(String[] args)
            throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException {

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

        Class<Test> clazz = Test.class;
        Method[] mtds = clazz.getMethods();
        for (Method method : mtds) {
            // 判断方法上有没有注解
            boolean hasAnno = method.isAnnotationPresent(CacheInMap.class);
            Object result = Null ; 

            // Ignore free methods annotated 
            IF (! HasAnno) {
                 Continue ; 
            } 

            // Get the number of parameters methods 
            int ParamCount = method.getParameterCount ();
             IF (ParamCount == 0 ) { 
                Result = Method.invoke ( clazz.newInstance ()); 
            } the else  IF (== ParamCount. 1 ) { 
                Result = Method.invoke (clazz.newInstance (), "" ); 
            } 

            // Get annotation 
            CacheInMap anno = method.getAnnotation (CacheInMap.class);
            if ("".equals(anno.key())) {
                String methodName = method.getName();
                map.put(methodName, result);
            } else {
                map.put(anno.key(), result);
            }
        }

        printMap(map);
    }

    public static void printMap(Map<String, Object> map) {
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            System.out.println(String.format("key:%s, value:%s", entry.getKey(), entry.getValue()));
        }
    }

}

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD, ElementType.ANNOTATION_TYPE })
@interface CacheInMap {
    String key() default "";
}

class Test {

    @CacheInMap(key = "qwer")
    public String method1(String str) {
        return "This is Method1";
    }

    @CacheInMap
    public int method2() {
        return 1024;
    }

    public double method3() {
        return 3.141592653;
    }
}

 The output of the above code #:

key:method2, value:1024
key:qwer, value:This is Method1

Guess you like

Origin www.cnblogs.com/lwmp/p/11496503.html