java 基础之注解

1.jdk常见注解:@Overload 、 @Deprecated 、 @Suppvisewarnings

2.注解分类:源码注解、编译时注解、运行时注解、元注解(注解的注解),标识注解(没有成员的注解)

3.元注解

@Target({ElementType.METHOD , ElementType.TYPE})//作用域
@Retention(RetentionPolicy.RUNTIME)//注解安生命周期分类
@Inherited//允许子类继承
@Documented//生成doc时会包含注解的信息

4.自定义写法:

1.使用@interface定义注解
2.成员必须以无参无异常方式声明
3.成员类型必须是原始类或String、Class、Annotation、Enumeration
4.当注解只有一个成员时,成员名必须为value(),使用时赋值时可忽略成员名和“=”
5.可以用default为成员赋默认值
6.被注解的类只能继承被注解的类有效,接口无效。

5.注解的定义

@Target({ElementType.METHOD , ElementType.TYPE})//作用域
@Retention(RetentionPolicy.RUNTIME)//注解安生命周期分类
@Inherited//允许子类继承
@Documented//生成doc时会包含注解的信息
public @interface Demo {//使用@interface定义注解
    
    String desc();//成员必须以无参无异常方式声明
    
    //Object haha();//成员类型必须是原始类或String、Class、Annotation、Enumeration
    
//    String value() default "hah" ;//当注解只有一个成员时,成员名必须为value(),赋值时可忽略成员名和“=”
    
    int age() default 18;//可以用default为成员赋默认值
    
}

 6.自定义注解的使用

  

    @Demo(desc="解析类上的注解")
    class PassAnn{
        @Demo(desc="解析方法上的注解",age=20)
        public void test(){}
        
    }

    @Demo(desc="haha",age = 20)
    private static void test1() {
        try {
            Class forName = Class.forName("com.itcast.test.Test4$PassAnn");
            boolean isExist = forName.isAnnotationPresent(Demo.class);
            if (isExist) {
                Demo demo1 = (Demo)forName.getAnnotation(Demo.class);
                System.out.println("desc:"+demo1.desc()+" , age:"+demo1.age());
            }
            
            Method[] methods = forName.getMethods();
            for (Method method : methods) {
                Annotation[] annotations = method.getAnnotations();
                for (Annotation annotation : annotations) {
                    if (annotation instanceof Demo ) {
                        Demo demo2 = (Demo)annotation;
                        System.out.println("desc:"+demo2.desc()+" , age:"+demo2.age());
                    }
                    
                }
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        
    }

 

posted @ 2015-08-05 08:34  小小攻城师  阅读(300)  评论(0编辑  收藏  举报