注解

注解-----Annotation

Annotation的作用:

  不是程序本身,可以对程序做出解释(这一点和注解(comment)没什么区别)

  可以被其他程序(比如编译器)读取

 

@Override:定义在java.lang.Override中,此注释只适用于修辞方法,表示一个方法声明打算重写超类中的另一个方法声明

@Deprecated:定义在java.lang.Deprecated中,此注释可以适用于修辞方法,属性,类,表示不鼓励程序员使用这样的元素,

@SuppressWarnings:定义在java.lang.SuppressWarnings中,用来抑制编译时的警告信息,需要添加一个参数才可以使用,这些参数是已经定义好的

  @SuppressWarnings("all")

  @SuppressWarnings("unchecked")等

 

元注解

package com.annotation;

import java.lang.annotation.*;

//测试元注解
@MyAnnotation
public class Test01 {


    public void test(){

    }
}

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

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

//Documented 表示是否将我们的注解生成在java.doc文档中
    @Documented

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

}

自定义注解

package com.annotation;

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

public class Test02 {
    //注解可以显示赋值,如果没有默认值,我们就必须给注解赋值
    @MyAnnotation01(age = 18,source = {"110","119","120"})
    public void test(){

    }

    //只有一个属性的话 且是value value可以省略不写
    @MyAnnotation02("可乐")
    public void test02(){}
}

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

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

 

posted @ 2022-05-11 10:20  长空扯淡  阅读(29)  评论(0)    收藏  举报