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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 李井山 中级黑马   /  2012-3-27 15:50  /  1335 人查看  /  4 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

Annotation的视频我看了,讲了注解的位置,持续时间和属性,但我还是不知道注解和他所修饰的属性,方法什么的有什么关系啊?

4 个回复

倒序浏览
利用Annotation可以进行反射
先定义
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation
{
        String hello() default "shengsiyuan";

        String world();
}
回复 使用道具 举报
@MyAnnotation(hello = "beijing", world = "shanghai")
public class MyTest
{
        @MyAnnotation(hello = "tianjin", world = "shangdi")
       
       
        public void output()
        {
                System.out.println("output something!");
        }
}
在应用Anntation
回复 使用道具 举报


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

public class MyReflection
{
        public static void main(String[] args) throws Exception
        {
                MyTest myTest = new MyTest();
               
                Class<MyTest> c = MyTest.class;
               
                Method method = c.getMethod("output", new Class[]{});
               
                if(method.isAnnotationPresent(MyAnnotation.class))
                {
                        method.invoke(myTest, new Object[]{});
                       
                        MyAnnotation myAnnotation = method.getAnnotation(MyAnnotation.class);
                       
                        String hello = myAnnotation.hello();
                        String world = myAnnotation.world();
                       
                        System.out.println(hello + ", " + world);
                }
               
                Annotation[] annotations = method.getAnnotations();
               
                for(Annotation annotation : annotations)
                {
                        System.out.println(annotation.annotationType().getName());
                }
               
               
               
               
               
               
               
               
               
               
               
               
               
               
               
               
               
               
               
        }
}
测试一下
结果是
output something!
tianjin, shangdi
MyAnnotation
回复 使用道具 举报
还有在junit4中也是用的注解
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马