得到注解后,如果获取注解里面的值?

代码如下,A、B是两个注解,Test是测试的demo

 package com.rgy.test;

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

@Retention(RUNTIME)
@Target({ FIELD, METHOD })
public @interface A {
    String aId();
    String aName();
}

 package com.rgy.test;

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

@Retention(RUNTIME)
@Target({ FIELD, METHOD })
public @interface B {
    String bId();
    String bName();
}

 package com.rgy.test;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;

public class Test {

    @A(aId = "a1", aName = "a1")
    @B(bId = "b1", bName = "b1")
    private String id;

    @A(aId = "a2", aName = "a2")
    @B(bId = "b2", bName = "b2")
    private String name;

    private static void test() {
        Field[] declaredFields = Test.class.getDeclaredFields();
        for (Field field : declaredFields) {
            Annotation[] annotations = field.getAnnotations();
            for (Annotation annotation : annotations) {
                System.out.println(annotation);
            }
        }
    }

    public static void main(String[] args) throws InstantiationException, IllegalAccessException {
        test();
    }
}

你拿到Filed的时候,不要用getAnnotations()这个方法,这是获取这个Filed上的所有注解,你不好具体处理,你可以使用这个方法

 getAnnotation(A.class)

就可以获取当前Filed上的注解A的对象,然后就可以取到注解里你想要的属性了值

 A a = getAnnotation(A.class);
 String aId = a.aId();

B注解的话,也是类似这么做

http://www.cnblogs.com/panxuejun/p/6089297.html

可以通过反射读取相关信息。