Java基础:注解篇

1.内置注解

package com.cl.annotation;

import java.util.ArrayList;

//三个常用的内置注解
//@Override 重写注解
//@Deprecated 不推荐程序员使用,但是可以使用,或者存在更好的方式
//@SuppressWarnings("all")//镇压警告

public class Test01 extends Object {

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

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

    @SuppressWarnings("all")//镇压警告
    public void test02(){
        ArrayList lis = new ArrayList();
    }

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

2.元注解

package com.cl.annotation;

import java.lang.annotation.*;
//什么是元注解,
//所谓元注解其实就是可以注解到别的注解上的注解,被注解的注解称之为组合注解,组合注解具备其上元注解的功能.

//四种元注解;
//@Target
//@Retention
//@Documented
//@Inherited


//测试元注解

@MyAnnotation
public class Test02 {

}

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

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

//Documented 表示是否将注解生成在JAVAdoc(文档)中
@Documented

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

}

3.自定义注解

package com.cl.annotation;

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

//自定义注解
public class Test03 {
    //注解可以显示赋值,如果没有默认值,就必须给注解赋值
    @MyAnnotation2(age = 18,name = "king")
    public void test(){}

    @MyAnnotation3("king")
    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() default {"黑龙江"};
}

@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)

//当自定义注解只有一个值是课用value命名这样就不用设置默认值了
@interface MyAnnotation3{
    String value();
}

 

posted @ 2020-09-19 20:59  凸然猿  阅读(122)  评论(1编辑  收藏  举报