JAVA注解基础

什么是注解

注解是插到源代码中的标签,使用其他工具可以对其进行处理。

注解语法

注解的定义和接口有点像,所有注解都扩展自java.lang.annotation.Annotation

@interface FirstAnnotation{
    int id();
    String name() default "default";
}

注解元素的类型

在这里插入图片描述

注解元素简化语法

使用注解时需要指定元素,如果没有指定,那么两种可能

  1. 注解中没有元素
  2. 注解中所有的元素都有默认值
@FirstAnnotation
@SecondAnnotation
public class Demo{
    public static void main(String[] args) {

    }
}

// 定义两个注解
@interface FirstAnnotation{}

@interface SecondAnnotation{
    String name() default "default";
}

如果注解元素有一个特殊的名字value,并且没有指定其他元素,则可以忽略掉元素名及等号

@ThirdAnnotation("默认值")
public class Demo{
    public static void main(String[] args) {

    }
}

@interface ThirdAnnotation{
    int id() default 0;
    String value();
}

如果注解元素值是一个数组,用{}。如果数组元素只有一个值,那么可以忽略括号

// 给直接的数组元素赋值
@FourthAnnotation(color = {"red","green"})
public class Demo<T>{
    public static void main(String[] args) {

    }
}

// 数组元素中只有一个值可以忽略括号
@FourthAnnotation(color = "red")
public class Demo{
    public static void main(String[] args) {

    }
}

@interface FourthAnnotation{
    String[] color();
}

元注解

元注解是注解注解的注解。

@Target

在这里插入图片描述
没有@Target限制的注解可以应用于任何项上

@Retention

在这里插入图片描述

@Document

生成的javadoc会含有这条注解

@Inherited

注解只能应用于类上,如果一个类具有继承注解,那么它的所有子类都自动具有同样类型的注解

理解不深,待续。。。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值