Java教程

Java注解全面总结,阿里专家原创

本文主要是介绍Java注解全面总结,阿里专家原创,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

=====

@Target


通过@Target进行添加到注解中,说明了Annotation所修饰的对象范围:Annotation可被用于 packages、types(类、接口、枚举、Annotation类型)、类型成员(方法、构造方法、成员变量、枚举值)、方法参数和本地变量(如循环变量、catch参数)。在Annotation类型的声明中使用了@target可更加明晰其修饰的目标,用于什么地方,修饰什么东西,如下常用的几种方式。

  • CONSTRUCTOR: 用于描述构造器

  • FIELD:用于描述域

  • LOCAL_VARIABLE:用于描述局部变量

  • METHOD:用于描述方法

  • PACKAGE:用于描述包

  • PARAMETER:用于描述参数

  • TYPE:用于描述类、接口(包括注解类型) 或enum声明

    如下代码

@Target({ElementType.FIELD,ElementType.METHOD}) //多个的时候使用{}括起来,然后用逗号分隔开

public @interface TargetTest {

} 

@Retention


该注解是表示我们在运行或者编译时的一个保留状态,指示要保留带注释类型的注释的时间长度。

  • SOURCE:在源文件中有效(即源文件保留),在编译时将其抛弃掉。

  • CLASS:在class文件中有效(即class保留),不会添加载到JVM中

  • RUNTIME:在运行时有效(即运行时保留),这个和我们常用的加载是一致的,运行时会加载到JVM中,一般通过反射可获取到,一般这个是我们常用的。

@Retention(RetentionPolicy.RUNTIME)//在使用该注解其,只能选择其中一种属性,不能定义多个

public @interface RetentionTest {

} 

@Documented


@Documented用于描述其它类型的annotation应该被作为被标注的程序成员的公共API。

如下代码

@Documented //添加文档注解

@Target(ElementType.FIELD)

@Retention(RetentionPolicy.RUNTIME)

public @interface AnnotationTest {

} 

@Inherited:


@Inherited元注解是一个标记注解, @Inherited阐述了某个被标注的类型是被继承的。如果一个使用了@Inherited修饰的annotation类型被用于一个class,则这个annotation将被用于该class的子类。

@Documented

@Target(ElementType.FIELD)

@Retention(RetentionPolicy.RUNTIME)

@Inherited  //添加继承注解

public @interface AnnotationTest {

} 

@Repeatable


这个是在java8添加的注解特性,@Repeatable的值表示可重复注释类型的包含注释类型。

@Target({ElementType.TYPE,ElementType.METHOD})

@Retention(RetentionPolicy.RUNTIME)

public @interface Repeatables {

    RepeatablesTest[] value();

}

@Repeatable(Repeatables.class)

public @interface RepeatablesTest {

    String value() default "哈哈哈";

} 

例子

==

我们简单的介绍了注解的常用的5个注解元,解下来我们通过例子来实现注解。

代码如下,根据上面的提示我们进行测试。

在看例子之前我们先来了解一下常用的几个方法。

  • Class.getAnnotations() 获取所有的注解,包括自己声明的以及继承的

  • Class.getAnnotation(Class< A > annotationClass) 获取指定的注解,该注解可以是自己声明的,也可以是继承的

  • Class.getDeclaredAnnotations() 获取自己声明的注解

  • Class.getDeclaredField(String name); //获取该类的声明字段

  • Class.getDeclaredMethods();//返回的是一个Method[]数组

@Documented

@Target({ElementType.TYPE,ElementType.METHOD})

@Retention(RetentionPolicy.RUNTIME)

public @interface AnnotationTest {

    String name() default "小明"; //表示默认为小明。

} 

@AnnotationTest() //在该类添加注解

public class TestAnnotationMain {

public static void main(String[] args) {

    boolean hasAnnotation = TestAnnotationMain.class.isAnnotationPresent(AnnotationTest.class);

    if (hasAnnotation) {

        AnnotationTest annotation = TestAnnotationMain.class.getAnnotation(AnnotationTest.class);

        System.out.println(annotation.name());

    }



}

}



打印输出结果:



![](https://upload-images.jianshu.io/upload_images/3012005-1f456a2d492413d6.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1000/format/webp)



如果我们想更改name的值可以这么弄



@AnnotationTest(name = “小刚”)

public class TestAnnotationMain {

public static void main(String[] args) {

    boolean hasAnnotation = TestAnnotationMain.class.isAnnotationPresent(AnnotationTest.class);

    if (hasAnnotation) {

        AnnotationTest annotation = TestAnnotationMain.class.getAnnotation(AnnotationTest.class);

        System.out.println(annotation.name());

    }

}

}



![](https://upload-images.jianshu.io/upload_images/3012005-037c41da49c434e1.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1000/format/webp)



如果我们想给一个类的属性进行赋值可以这么做  

1.创建一个注解如下



@Documented

@Retention(RetentionPolicy.RUNTIME)

public @interface AnnotationTest1 {

String value(); //value来定义

}



2.引用该主解



public class Test {

@AnnotationTest1(value = "小云") //引用注解进行赋值

public String name;

}



3.测试



public class TestAnnotation1Main {

public static void main(String[] args) {

    try {

        Field name = Test.class.getDeclaredField("name");//该该类的字段

        name.setAccessible(true); 

        AnnotationTest1 annotationTest1 = name.getAnnotation(AnnotationTest1.class);//获取该字段的注解

        if (annotationTest1 != null) {

            System.out.println(annotationTest1.value()); //输出值

        } 

    } catch (NoSuchFieldException e) {

        e.printStackTrace();

    }

}

}



> 获取方法上的注解类 如AnnotationTest2



@Retention(RetentionPolicy.RUNTIME)

@Target(ElementType.METHOD)

public @interface AnnotationTest2 {

 //todo无任何方法或者属性

}

public class Test {



    @AnnotationTest1(value = "小云")

    public String name;



    @AnnotationTest2 //目的获取该AnnotationTest2 

    public void fun() {

        System.out.println("方法执行");

    }

} 

```



获取



```



# **读者福利**

**[CodeChina开源项目:【一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频】](https://codechina.csdn.net/m0_60958482/java-p7)**

![秋招我借这份PDF的复习思路,收获美团,小米,京东等Java岗offer](https://www.www.zyiz.net/i/ll/?i=img_convert/e666ea8d298a3797799d0d0706631c64.png)

**更多笔记分享**

![秋招我借这份PDF的复习思路,收获美团,小米,京东等Java岗offer](https://www.www.zyiz.net/i/ll/?i=img_convert/50509b2b55697dfab9e3c8453fd302ff.png)

云")

    public String name;



    @AnnotationTest2 //目的获取该AnnotationTest2 

    public void fun() {

        System.out.println("方法执行");

    }

} 

```



获取



```



# **读者福利**

**[CodeChina开源项目:【一线大厂Java面试题解析+核心总结学习笔记+最新讲解视频】](https://codechina.csdn.net/m0_60958482/java-p7)**

[外链图片转存中...(img-1qpQB7tu-1630903078199)]

**更多笔记分享**

[外链图片转存中...(img-MBVVU3uy-1630903078200)]

这篇关于Java注解全面总结,阿里专家原创的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!