A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 包志恒 黑马帝   /  2011-7-26 17:23  /  2262 人查看  /  4 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

package Annotion;

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

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE ,ElementType.METHOD})
public @interface MyAnnotion {
   
        String value();
        String color() default "red";
}
package Annotion;

@MyAnnotion(value = "acc")
public class AnnotionTest {

        /**
         * @param args
         */
        @MyAnnotion(value="str",color="green")
        public static void main(String[] args) {
                // TODO Auto-generated method stub
                if(AnnotionTest.class.isAnnotationPresent(MyAnnotion.class))
                {
                        MyAnnotion annotation = (MyAnnotion) AnnotionTest.class.getAnnotation(MyAnnotion.class);
                        System.out.println(annotation.value());
                        System.out.println(annotation.color());
                }
                printString("看灰机");
        }

        @Deprecated
        public static void printString(String str)
        {
                System.out.println(str);
        }

}
请问我在方法上的@MyAnnotion(value="str",color="green")
为什么打印出来的还是
acc
red
为什么不是
str
green 呢

评分

参与人数 1技术分 +2 收起 理由
admin + 2 看看杰伦怎么回答的!

查看全部评分

4 个回复

倒序浏览
黑马网友  发表于 2011-7-26 18:28:50
沙发
使用您的语句,获得的是类上的Annotation。
若想获得某个方法的Annotation,则需要先获取那个方法的Method对象,然后再调用这个Method对象的Annotation。
范例1:如您所愿。[code=java]@MyAnnotion(value = "acc")
public class AnnotationTest {

        /**
         * @param args
         * @throws NoSuchMethodException
         * @throws SecurityException
         */
        @MyAnnotion(value="str",color="green")
        public static void main(String[] args) throws SecurityException, NoSuchMethodException {
                // TODO Auto-generated method stub
                if(AnnotationTest.class.isAnnotationPresent(MyAnnotion.class))
                {
                        MyAnnotion annotation = (MyAnnotion) AnnotationTest.class.getMethod("main",String[].class).getAnnotation(MyAnnotion.class);
                        System.out.println(annotation.value());
                        System.out.println(annotation.color());
                }
                printString("看灰机");
        }

        @Deprecated
        public static void printString(String str)
        {
                System.out.println(str);
        }

} [/code]本范例的核心代码:
“AnnotationTest.class.getMethod("main",String[].class).getAnnotation(MyAnnotion.class); ”
程序输出结果:[code=java]str
green
看灰机[/code]

评分

参与人数 1技术分 +3 收起 理由
admin + 3 杰伦多得满天飞啊!

查看全部评分

回复 使用道具 举报
黑马网友  发表于 2011-7-26 18:42:34
藤椅
哈哈  原来如此 灰常感谢  对了你怎么头像和那个周杰伦的一样啊 你是他的偶像么:lol
回复 使用道具 举报
黑马网友  发表于 2011-7-26 19:08:03
板凳
那个周杰伦暂时消失了。
如果您找他有事,去咱们的 情感发泄区,也许会有一些蛛丝马迹。
回复 使用道具 举报
顶一个啊!!
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马