JAVA自定义注解

本文详细介绍了Java注解的使用,特别是元注解@Retention、@Target、@Document和@Inherited的功能及应用场景。通过实例演示了如何在类和方法上使用自定义注解,并通过反射获取注解信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

java注解使用是相当频繁,特别是在搭建一些框架时,用到类的反射获取方法和属性,用的尤其多。

 

java中元注解有四个: @Retention @Target @Document @Inherited;

   @Retention:注解的保留位置         

      @Retention(RetentionPolicy.SOURCE)   //注解仅存在于源码中,在class字节码文件中不包含

      @Retention(RetentionPolicy.CLASS)     // 默认的保留策略,注解会在class字节码文件中存在,但运行时无法获得,

      @Retention(RetentionPolicy.RUNTIME)  // 注解会在class字节码文件中存在,在运行时可以通过反射获取到

  

  @Target:注解的作用目标

        

        @Target(ElementType.TYPE)   //接口、类、枚举、注解

        @Target(ElementType.FIELD) //字段、枚举的常量

        @Target(ElementType.METHOD) //方法

        @Target(ElementType.PARAMETER) //方法参数

        @Target(ElementType.CONSTRUCTOR)  //构造函数

        @Target(ElementType.LOCAL_VARIABLE)//局部变量

        @Target(ElementType.ANNOTATION_TYPE)//注解

        @Target(ElementType.PACKAGE) ///包   

 

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

 

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

package wg.test;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @Auther tang
 * @Date 2018/9/4
 * @Description
 */
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface AnnotationClass {

    String color() default "red";//定义一个方法返回值类型String,赋值时类似javaBean的属性,color = red

    String value();//如果只有这个属性,赋值的时候直接写值就行

    String[] arrayAttr() default {"111","222","33"};


}
package wg.test;

import java.lang.reflect.Array;
import java.util.Arrays;

/**
 * @Auther tang
 * @Date 2018/9/4
 * @Description
 */
@AnnotationClass(color = "blue" , value = "123",arrayAttr = {"q","w","e"})
public class AnnotationTest {
    @AnnotationClass("678")
    public static void main(String[] args) {
        if(AnnotationTest.class.isAnnotationPresent(AnnotationClass.class)){//判断AnnotationClass是不是注解类
            //获取注解类
            AnnotationClass annotationClass = AnnotationTest.class.getAnnotation(AnnotationClass.class);
            System.out.println(annotationClass.color());
            System.out.println(annotationClass.value());
            System.out.println(Arrays.asList(annotationClass.arrayAttr()));
        }


    }
}

你要自己搭框架的时候,就会用到反射,用到反射那么注解就会用到,用到注解那么那些java原生注解,自定义注解你得去查啊,然后就会查到java api,去官网下一个java api,上面都有的。便于平时查阅

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值