Annotation 注解

Annotation 注解,第1张

Annotation 注解 Annotation 注解

文章目录


Tips
    一定程度上 :框架 = 注解 + 反射 + 设计模式
使用示例

示例一:生成文档相关的注解

    @author:标明开发该类模块的作者,多个作者之间使用,分割@version: 标明该类模块的版本@see: 参考转向,也就是相关主题@since: 从哪个版本开始增加的@param: 对方法中某参数的说明,如果没有参数就不能写@return: 对方法返回值的说明,如果方法的返回值类型是void就不能写@exception: 对方法可能抛出的异常进行说明 ,不能写方法没有用throws抛出的异常

其中

    @param @return 和 @exception 这三个标记都是只用于方法的。@param的格式要求:@param 形参名 形参类型 形参说明@return 的格式要求:@return 返回值类型 返回值说明@exception的格式要求:@exception 异常类型 异常说明 @param和@exception可以并列多个
package Atest;


public class Test {
    
    public static void main(String[] args) {
    }

    
    public static double getArea(double radius) {
        return Math.PI * radius * radius;
    }
}

示例二:在编译时进行格式检查(JDK内置的三个基本注解)

    @Override: 限定重写父类方法, 该注解只能用于方法@Deprecated: 用于表示所修饰的元素(类, 方法等)已过时。通常是因为所修饰的结构危险或存在更好的选择@SuppressWarnings: 抑制编译器警告
public class Test {
    public static void main(String[] args) {
        @SuppressWarnings("unused") int a = 10;
    }

    @Deprecated
    public void print() {
        System.out.println("过时的方法");
    }

    @Override
    public String toString() {
        return "重写的toString方法()";
    }
}

示例三:跟踪代码依赖性,实现替代配置文件功能

    Servlet3.0提供了注解(annotation),使得不再需要在web.xml文件中进行Servlet的部署。spring框架中关于“事务”的管理
自定义注解
    注解声明为:@interface内部定义成员,通常使用value表示可以指定成员的默认值,使用default定义如果自定义注解没有成员,表明是一个标识作用。
    同理没有成员的接口叫做标识接口
public @interface MyAnnotation {
 	String value();
    //String value() default "hello";
}
元注解

元注解:对现有的注解进行解释说明的注解

    Retention:指定所修饰的 Annotation 的生命周期
      SOURCE
      CLASS(默认行为)
      RUNTIME(只此可通过反射获取)Target:用于指定被修饰的 Annotation 能用于修饰哪些程序元素(出现的频率较低)documented:表示所修饰的注解在被javadoc解析时,保留下来。Inherited:被它修饰的 Annotation 将具有继承性。
jdk 8新特性:可重复注解、类型注解 可重复注解
    在MyAnnotation上声明@Repeatable,成员值为MyAnnotations.classMyAnnotation的Inherited(运行时报错)、Target和Retention等元注解与MyAnnotations相同。
//jdk 8之前的写法:
//MyAnnotation
@MyAnnotations({@MyAnnotation(value="hi"),@MyAnnotation(value="hi")})

//MyAnnotations
public @interface MyAnnotations {
    MyAnnotation[] value();
}


//jdk 8之后的写法:
//MyAnnotation
@Inherited
@Repeatable(MyAnnotations.class)
@Retention(RetentionPolicy.RUNTIME)
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE,TYPE_PARAMETER,TYPE_USE})
public @interface MyAnnotation {
    String value() default "hello";
}

//MyAnnotations
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
public @interface MyAnnotations {
    MyAnnotation[] value();
}
类型注解

用于@Target({ })中

    ElementType.TYPE_PARAMETER :可写在类型变量的声明语句中(如:泛型声明)。ElementType.TYPE_USE :可写在使用类型的任何语句中。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/zaji/5722012.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-18
下一篇 2022-12-18

发表评论

登录后才能评论

评论列表(0条)

保存