0
点赞
收藏
分享

微信扫一扫

内置注解、元注解、自定义注解

yundejia 2022-01-27 阅读 29

内置注解

//@SuppressWarnings("all") //镇压警告
public class Test01 extends Object {

    //Override  重写的注解
    @Override
    public String toString() {
        return super.toString();
    }

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

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


运行结果:
Deprecated

元注解

import java.lang.annotation.*;

public class Test02 {
    public void test(){

    }
}

//定义一个注解
//Target 表示我们的注解用在哪些地方
@Target(value = {ElementType.METHOD,ElementType.TYPE})

//Retention 表示我们的注解在什么地方有效
//runtime>class>sources
@Retention(value = RetentionPolicy.RUNTIME)

//Documented 表示是否将我们的注解生成在JAVAdoc中
@Documented

//Inherited 子类可以继承父类的注解
@Inherited
@interface MyAnnotation{

}

自定义注解

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

//自定义注解
public class Test03 {
    //注解可以显示赋值,也可以用default设置默认值
    @MyAnnotation2(name = "阿涛",school = "轻工大")
    public void test() {

    }
    //注解中只有一个参数时,可以用value命名,此时前面“value=”可以省略
    @MyAnnotation3("涛")
    public void test2(){

    }
}

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation2{
    //注解的参数:参数类型+参数名();
    String name() default "";
    int age() default 0;
    int id() default -1;//默认值为-1,代表不存在
    String[] school();
}

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation3{
    String value();
}

举报

相关推荐

0 条评论