注解与反射

什么是注解?

Annotation始于JDK5.0

Annotation作用:

  • 不是程序本身,可以对程序作出解释(与注释comment无异)

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

Annotation格式:

  • @+注释名(参数值)

  • 例如:@SuppressWarnings(Value="unchecked")

Annotation使用方式:

  • 可在package,class,method,field等上面,相当于添加额外的辅助信息,通过反射机制编程实现对元数据的访问

内置注解

@Override:重写方法

@Override
public String toString() {
    return super.toString();
}

@Deprecated:不鼓励使用,但不是禁止使用

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

@SuppressWarnings:镇压警告

@SuppressWarnings("all")
public void test02(){
    List list = new ArrayList();
}
//常用的参数
@SuppressWarnings("all")
@SuppressWarnings("unchecked")
@SuppressWarnings(value = {"unchecked", "deprecation"})
//使用的范围
==@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})==

元注解

作用:负责注解其他注解,Java定义了4个标准的meta-annotation类型,被用来提供对其他annotation类型作为说明

均继承与java.long.annotation

@Target:用于描述注解范围(例如该注解使用在什么地方)

public class Test02 {
    @MyAnnotation
    public void Test02(){
    }
}
//对注解的约束,定义只在类中使用,其他地方则会标红报错
@Target(value = ElementType.METHOD)
@interface MyAnnotation{
}
//使用范围(源码解释)
public enum ElementType {
    /** Class, interface (including annotation type), or enum declaration */
    TYPE,

    /** Field declaration (includes enum constants) */
    FIELD,

    /** Method declaration */
    METHOD,

    /** Formal parameter declaration */
    PARAMETER,

    /** Constructor declaration */
    CONSTRUCTOR,

    /** Local variable declaration */
    LOCAL_VARIABLE,

    /** Annotation type declaration */
    ANNOTATION_TYPE,

    /** Package declaration */
    PACKAGE,

    /**
     * Type parameter declaration
     *
     * @since 1.8
     */
    TYPE_PARAMETER,

    /**
     * Use of a type
     *
     * @since 1.8
     */
    TYPE_USE
}

@Retention:表示需要在什么级别保存该注释信息,用于描述注解的生命周期(SOURCE<CLASS<RUNTIME)

@Retention(value = RetentionPolicy.SOURCE)
@Retention(value = RetentionPolicy.CLASS)
@Retention(value = RetentionPolicy.RUNTIME)

@Documented:说明该注解被包含在javadoc中

@Inherited:说明子类可以继承父类中的该注解

 

posted @ 2022-09-08 23:34  里牧之  阅读(29)  评论(0)    收藏  举报