你的位置:首页 > 信息动态 > 新闻中心
信息动态
联系我们

注解和反射-part01注解

2021/11/23 22:21:37

1.注解:

什么是注解?

有 检查和约束作用的功能

1.1、内置注解:

注解有那些?

  • @Override 重写的注解
  • @Deprecated 不推荐程序员使用,但是可以使用,或者存在更好的方式
  • @SuppressWarnings 镇压警告
package cim.shuang.annotation;

import java.util.ArrayList;
import java.util.List;

//什么是注解
public class Test01 extends Object{
    // @Override 重写的注解
    @Override
    public String toString() {
        return super.toString();
    }

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

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

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

1.2、元注解:

  • 元注解的作用就是负责注解其他注解,Java定义了4个标准的meta-annotation类型,他们被用来提供对其他annotation类型作说明.
  • 这些类型和它们所支持的类在java.lang.annotation包中可以找到.( @Target , @Retention ,@Documented , @lnherited )
    • @Target:用于描述注解使用的范围【重点】
    • @Retention 表示需要在什么级别保存该注释信息【重点】
      • (SOURCE<CLASS<RUNTIME)原代码<class类<运行时
    • @Documented 说明该注解将被包含在javadoc中
    • @lnherited 说明子类可以继承父类中的该注解
package cim.shuang.annotation;

import java.lang.annotation.*;

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

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

//@Documented 表示是否将我们的注解生成在JAVAdao中
@Documented

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

}

1.3、自定义注解

  • 使用@interface自定义注解时﹐自动继承了java.lang.annotation.Annotation接口
  • 分析:
    • @interface用来声明一个注解﹐格式: public @interface注解名{定义内容}
    • 其中的每一个方法实际上是声明了一个配置参数.
    • 方法的名称就是参数的名称.
    • 返回值类型就是参数的类型(返回值只能是基本类型,Class , String , enum ).
    • 可以通过default来声明参数的默认值
    • 如果只有一个参数成员,一般参数名为value
    • 注解元素必须要有值﹐我们定义注解元素时,经常使用空字符串,0作为默认值.
package cim.shuang.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(name="123")
    public void test(){ }
    //默认为value,可以省略
    @MyAnnotation3("13456")
    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 [] schools() default {"西部开源","清华大学"};
}

@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation3{
    String value();
}