Annotation的一个小问题

java_pojo 2012-03-06 09:20:02

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呢.各位大侠们指较下.
...全文
42 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
BadPattern 2012-03-06
  • 打赏
  • 举报
回复
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级别的么,这样就会被丢弃了
  • 打赏
  • 举报
回复
不是a.Value();a.Mehtod();吗?为嘛是a?
java_pojo 2012-03-06
  • 打赏
  • 举报
回复
我自定义的Annotation类少了个东西


package annotation;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {

String Mehtod();

String Value();
}
BadPattern 2012-03-06
  • 打赏
  • 举报
回复
怎么解决的,我还在测试呢
java_pojo 2012-03-06
  • 打赏
  • 举报
回复
哎,问题自己解决了.第一个答的人我把分送给你了
java_pojo 2012-03-06
  • 打赏
  • 举报
回复
被上我定义的Annotation类.

package annotation;

public @interface MyAnnotation {

String Mehtod();

String Value();
}

62,623

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧