首页 > 编程语言 >JAVA学习笔记10-注解

JAVA学习笔记10-注解

时间:2023-02-25 14:33:46浏览次数:39  
标签:10 JAVA SuppressWarnings java value public 注解 class

目录

什么是注解

  • Annotation是JDK5.0引入的新技术
  • 作用:不是程序本身,可以对程序做出解释就像注释一样;可以被其他程序(比如编译器)读取
  • 格式:注解是以@注释名在代码中存在的,还可以添加一些参数值,例如:@SuppressWarnings(value="unchecked")
  • 可以在哪里使用?可以附加在package,class,method,field等上面,相当于给他们增加了额外的辅助信息,我们可以通过反射机制编程实现对这些元数据的访问

内置注解

  • @override:定义在java.lang.Override中,此注解只适用于修辞方法,表示一个方法声明打算重写超类中的另一个方法声明
  • @Deprecated:定义在java.lang.Deprecated中,此注解可以用于修辞方法、属性、类表示不鼓励程序员使用这样的元素,通常是因为它很危险或者存在更好的选择
  • @SuppressWarnings:定义在java.lang.SuppressWarning中,用来抑制编译时的警告信息
    与前面两个注解不同的是,SuppressWarnings需要添加参数才可以正常的使用,这些参数都是提前定义好的比如:
    1.@SuppressWarnings("all")
    2.@SuppressWarnings("unchecked")
    3.@SuppressWarnings(value={"unchecked","deprecation"})
    ......

示例代码可见Demo01.class

package com.learnAnnotation.leason;

public class Demo01 extends Object{
    @Override
    public String toString() {
        return super.toString();
    }

    @Deprecated
    public static void test1(){
        System.out.println("Deprecated");
    }

    @SuppressWarnings("all")
    public void test2(){
        int a = 10;
    }

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

元注解

  • @Target 表示我们的注解可以用在哪些地方
  • @Retention 表示我们的注解在程序运行的哪个阶段有效(runtime>class>sources)
  • @Documented 表示是否将我们的注解生成在javadoc中
  • @Inherited 子类可以继承父类的注解

示例代码请看Demo02.class

package com.learnAnnotation.leason;

import jdk.internal.org.objectweb.asm.tree.analysis.Value;

import java.lang.annotation.*;

@myAnnotation
public class Demo02 {

}

@Target(value = {ElementType.METHOD,ElementType.TYPE})
@Retention(value = RetentionPolicy.RUNTIME)
@Documented
@Inherited
@interface myAnnotation {

}

标签:10,JAVA,SuppressWarnings,java,value,public,注解,class
From: https://www.cnblogs.com/zbcgoal/p/17154355.html

相关文章