JAVA注解笔记

1 概念

Java注解是附加在代码中的一些元信息,用于一些工具在编译、运行时进行解析和使用,起到说明、配置的功能。

2 标准注解

常见的有:
@Override 重写的注解
@Deprecated 不鼓励使用的元素
@SuppresWarnings() 抑制警告

3 元注解

负责注解其他注解
@Target:描述注解的使用范围
@Retention:表示需要在什么级别保存该注释信息,描述注解的生命周期,在源代码中(SOURCE)、类文件中(CLASS)或者运行时(RUNTIME)。
(SOURCE<CLASS<RUNTIME
@Documented:说明该注解将被包含在javadoc中
@Inherited:说明子类可以继承父类中的该注解
使用示例:

//  自定义一个注解
//  Document 表示是否将注解生成在Javadoc中
    @Documented
//  Retention 表示注解在何时有效 Runtime >class >sources
    @Retention(RetentionPolicy.RUNTIME)
//  Target表示注解可以用在哪些地方
    @Target(value = {ElementType.METHOD,ElementType.TYPE})
//    子类可以继承父类的注解
    @Inherited
    @interface MyAnnotation{
}

3 自定义注解

使用@interface定义注解时,自动继承了java.lang.annotation.Annotation接口

  • 格式:
    public @interface 注解名{定义内容}
import java.lang.annotation.*;

public class test01 {

//  注解可以显示赋值,若有默认值可以不写,若没有默认值则必须给注解赋值
    @MyAnnotation(age = 1)
    public void test() {
    }

//  自定义一个注解 MyAnnotation
//  Document 表示是否将注解生成在Javadoc中
    @Documented
//  Retention 表示注解在何时有效 Runtime >class >sources
    @Retention(RetentionPolicy.RUNTIME)
//    Target表示注解可以用在哪些地方
    @Target({ElementType.METHOD,ElementType.TYPE})
//    子类可以继承父类的注解
    @Inherited
    @interface MyAnnotation{
//    注解的参数:参数类型+参数名();
//    使用default声明参数的默认值
        String name() default "";
        int age();//无默认值
}

//  自定义一个注解 MyAnnotation2
    @Documented
    @Retention(RetentionPolicy.RUNTIME)
    @Target({ElementType.METHOD,ElementType.TYPE})
    @Inherited
    @interface MyAnnotation2{
    //    如果只有一个参数成员,一般参数名为value
       String  value();
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值