注解与反射

1.注解

1.1 注解定义

给编译器看的解释,有些注解具有一定的功能性

1.2 内置注解

1.2.1 @Deprecated

此注解表示方法不在使用或者具有更好的方法替代

@Deprecated
public void test() {
		
}

在使用@Deprecated注解后,方法上面有出现删除线表示此方法不再使用或者不建议使用

1.2.2 @SuppressWarnings("all")

镇压警告

@SuppressWarnings("all")
	public void test02() {
		ArrayList l = new ArrayList();
	}

在没有加上@SuppressWarnings("all")注解钱,代码是会出现警告,加上注解后警告消失

1.2.3 @Override

表示重写方法

1.3 元注解

对注解类型进行注解

类型:

  • @Target() //指明注释应用范围
  • @Retention() //指明注释应用周期
  • @Documented
  • @Inherited

对于一个自定义注解,前两项是必须的,后两项可选择性注解

1.3.1 @Target()

public @interface Target {
    /**
     * Returns an array of the kinds of elements an annotation type
     * can be applied to.
     * @return an array of the kinds of elements an annotation type
     * can be applied to
     */
    ElementType[] value();
}

@Target()是指明定义的注解的应用范围

参数必须输入一个表示范围的变量,可以有以下选择

public enum ElementType {
    /** Class, interface (including annotation type), enum, or record
     * 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,
}

使用如下:

@Target(value= {ElementType.TYPE,ElementType.METHOD})  //指明注释应用范围

1.3.2 @Retention()

public @interface Retention {
    /**
     * Returns the retention policy.
     * @return the retention policy
     */
    RetentionPolicy value();
}

@Retention()说明该注解的生命周期,可以有三个选择

  • SOURCE
  • CLASS
  • RUNTIME(自定义注解的选项)

RUNTIME > CLASS > SOURCE

1.3.3 @Documented

1.3.4 @Inherited

1.4 自定义注解

对于自定义注解,可以在里面定义参数,参数格式如下:

参数类型 + 参数名称() [+ default 默认值]

不要忘记()

对于已经有默认值的参数,在使用注解时可以不进行定义

public class test1 {
	
	@Myannoaction(age = 10)
	@Myannoaction2("qwe")
	public void test() {
		
	}

}

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@interface Myannoaction{
	
	//注解参数格式: 参数类型 + 参数名称() [+ default 默认值]
	String name() default "Aer";
	int age();
}


@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@interface Myannoaction2{
	String value();
}
posted @ 2021-02-15 21:46  A,er  阅读(58)  评论(0)    收藏  举报