注解

注解的定义:

public @interface TestAnnotation {    
}

元注解:

对注解进行注解的注解,可以应用到注解上

// 设置注解的保留期
//@Retention(RetentionPolicy.RUNTIME)  注解可以保留到运行期间  会被加载到jvm中去
//@Retention(RetentionPolicy.CLASS)  注解可以保留到编译进行的时候,不会被加载到jvm中去
@Retention(RetentionPolicy.SOURCE)   //注解只会保留在源码中
public @interface TestAnnotation {    
}
//将注解中的元素包含到 Javadoc 中去。
@Documented
public @interface TestAnnotation {    
}
//定义了注解可以应用的地方
//@Target(ElementType.ANNOTATION_TYPE) //可以给注解添加注解
//@Target(ElementType.CONSTRUCTOR) //可以给构造函数添加注解
//@Target(ElementType.FIELD) //可以给字段属性添加注解
//@Target(ElementType.LOCAL_VARIABLE) //可以给局部变量添加属性
//@Target(ElementType.METHOD) //可以给方法添加属性
//@Target(ElementType.PACKAGE) //可以给包添加注解
//@Target(ElementType.PARAMETER) //可以给参数添加注解
@Target(ElementType.TYPE) //可以给类型添加注解,比如类型,枚举,接口
public @interface TestAnnotation {    
}

@Inherited

Inherited 是继承的意思,但是它并不是说注解本身可以继承,而是说如果一个超类被 @Inherited 注解过的注解进行注解的话,

那么如果它的子类没有被任何注解应用的话,那么这个子类就继承了超类的注解。

注解的属性

注解的属性也叫做成员变量。注解只有成员变量,没有方法。注解的成员变量在注解的定义中以“无形参的方法”形式来声明,

其方法名定义了该成员变量的名字,其返回值定义了该成员变量的类型。

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TestAnnotation {    
    int id();
    String msg();
}

public class Test1 {
    @TestAnnotation(id=1,msg="123")
    private void method1() {    
    }
}

 注解与反射

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface TestAnnotation {    
    int id();
    String msg();
}

@TestAnnotation(id=1,msg="123")
public class Test1 {
    public static void main(String[] args) {    
        // 判断是否应用了某个注解
        boolean hasAnnotation=Test1.class.isAnnotationPresent(TestAnnotation.class);
        System.out.println(hasAnnotation);
        
        if(hasAnnotation){
            //获取注解
            TestAnnotation testAnnotation=Test1.class.getAnnotation(TestAnnotation.class);
            
            System.out.println(testAnnotation.id()); //获取注解中的属性
            System.out.println(testAnnotation.msg());
        }
    }    
}

注解的应用

注解的基本语法,创建如同接口,但是多了个 @ 符号。注解主要给编译器及工具类型的软件用的。

注解的提取需要借助于 Java 的反射技术,反射比较慢,所以注解使用时也需要谨慎计较时间成本。

参考:http://www.importnew.com/23564.html

          https://www.cnblogs.com/xdp-gacl/p/3622275.html

https://blog.csdn.net/briblue/article/details/73824058/

 

转载于:https://www.cnblogs.com/yanliang12138/p/10329846.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值