package annotation;import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;public class Test { @MyAnnotation(Value="aa", Mehtod = "bb")
public void get() {
System.out.println("Method invoked");
}

public static void main(String[] args) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
Test t = new Test();
Method method = t.getClass().getMethod("get");
System.out.println(method.isAnnotationPresent(MyAnnotation.class));
method.invoke(t);
MyAnnotation a = method.getAnnotation(MyAnnotation.class);
System.out.println(a);
}
}
这个a的值是null,为什么呢?  还有System.out.println(method.isAnnotationPresent(MyAnnotation.class));这个输出是False, 是不是因为它是False才不能取到a的值.但怎么让它变成True呢.各位大侠们指较下.

解决方案 »

  1.   

    被上我定义的Annotation类.  package annotation;public @interface MyAnnotation { String Mehtod();

    String Value();
    }
      

  2.   

    我自定义的Annotation类少了个东西 
    package annotation;import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;@Retention(RetentionPolicy.RUNTIME)
    public @interface MyAnnotation { String Mehtod();

    String Value();
    }
      

  3.   

    不是a.Value();a.Mehtod();吗?为嘛是a?
      

  4.   

    public enum RetentionPolicy {
      SOURCE, // Annotation is discarded by the compiler
      CLASS, // Annotation is stored in the class file, but ignored by the VM
      RUNTIME // Annotation is stored in the class file and read by the VM
    }难道默认是SOURCE级别的么,这样就会被丢弃了