java注解的一些事(基础知识)

1.什么是注解
在这里插入图片描述

package com.qiu.annotation;public class Test01 {
    @Override//注解,重写的注解
    public String toString() {
        return "Test01{}";
    }
}

2.内置注解
在这里插入图片描述

package com.qiu.annotation;import java.util.ArrayList;public class Test01 {
    @Override//注解,重写的注解
    public String toString() {
        return "Test01{}";
    }
    //不推荐程序员使用,但是可以使用,或者存在更好的方式
    @Deprecated
    public static void test(){
        System.out.println("Deprecated");
    }
    @SuppressWarnings("all")//警告镇压
public void test02(){
    ArrayList<Object> objects = new ArrayList<>();
}    public static void main(String[] args) {
        test();
    }
}

3.元注解
在这里插入图片描述
4.自定义注解
在这里插入图片描述

package com.qiu.annotation;import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;public class Test03 {
    public static void main(String[] args) {
        Test03 test03 = new Test03();
        
    }
    
    
    
    //注解可以显示赋值,如果没有默认值,我们就必须给注解赋值
    @MyAnnotation2(age = 18,name = "chen")
    public void test(){
    
        
    }
    @MyAnnotation3("tatata")//如果是value,参数类型可以不写,其他值就不行
    public void test2(){
        
    }
}
@Target(value = {ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation2{
    //注解的参数:参数类型+参数名();
    String name() default "";
    int age() default 0;
    int id() default -1;//如果默认值为-1,表示不存在,index of,如果找不到就返回-1
    String[] schools() default {"南昌大学","清华大学"};
}
@Target(value = {ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation3{
    //注解的参数:参数类型+参数名();
    String value();
}
原创文章 32 获赞 52 访问量 651

猜你喜欢

转载自blog.csdn.net/qq_42400763/article/details/105756012
今日推荐