java注解学习


1. 什么是注解

注解是给程序看的,注释是给人看的。
注解

2. 内置注解

在这里插入图片描述

// 什么是注解
public class Test01 extends Object {
    // 重写的注解
    @Override
    public String toString() {
        return super.toString();
    }

    // Deprecated, 不推荐程序员使用,但是可以使用,或者存在更好的方式
    @Deprecated
    public static void test01() {
        System.out.println("Deprecated");
    }

    @SuppressWarnings("all")
    public void test02() {
        List<String> list = new ArrayList<>();
    }

    public static void main(String[] args) {
        test01();
    }
}

3. 元注解

在这里插入图片描述

public class Test02 {
    public void test() {

    }
}

// 定义一个注解
// Target,表示定义的注解可以用在什么地方
@Target(value = {ElementType.METHOD})
// Retention,表示定义的注解在什么地方还有效
// runtime>class>source
@Retention(RetentionPolicy.RUNTIME)
// 表示是否将定义的注解生产在JAVAdoc中
@Documented
// 子类可以继承父类的注解
@Inherited
@interface MyAnnotation {

}

4. 自定义注解

在这里插入图片描述

// 自定义注解
public class Test03 {
    // 注解可以显示赋值,如果没有默认值,则必须给注解赋值
    @MyAnnotation02(age = 18)
    public void test01() {
    }

    @MyAnnotation03("qinjiang")
    public void test02() {
    }
}

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation02 {
    // 注解的参数:参数类型 + 参数名 ();
    String name() default "";

    int age();

    int id() default -1;

    String[] schools() default {"清华", "北大"};
}

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation03 {
    // 若只有一个参数且使用value(),则使用时可不写参数名value
    String value();
}

参考

根据狂神注解视频学习
链接:https://www.bilibili.com/video/BV1p4411P7V3?p=4

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值