前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >如何自定义注解(how to customize the annotation in java)

如何自定义注解(how to customize the annotation in java)

原创
作者头像
CoffeeLand
修改2020-04-01 10:14:52
5660
修改2020-04-01 10:14:52
举报
文章被收录于专栏:CoffeeLand

Table of Contents

  • What is annotation?
  • How to customize the annotation?
  • How to get the value of the annotation?
  • References

What is annotation?

注解是是一种数据类型, 它是一个标记, 方便java在编译时遇到这个标记能采取进一步的action


How to customize the annotation?

steps to customize the annotation

  1. 使用@interface来定义注解接口
  2. 定义注解的生命周期@Retention(RetentionPolicy.RUNTIME)
    1. SOURCE 用在源文件上
    2. Class ,它是default的, 会在编译时被记录在class文件里, 但是在运行时不会被保留, 不可以通过反射去拿
    3. RUNTIME 会在编译时被记录在class文件里, 只有RunTime才可以通过反射去获取注解的属性值
代码语言:javascript
复制
/**
     * Annotations are to be discarded by the compiler.
     */
    SOURCE,

    /**
     * Annotations are to be recorded in the class file by the compiler
     * but need not be retained by the VM at run time.  This is the default
     * behavior.
     */
    CLASS,

    /**
     * Annotations are to be recorded in the class file by the compiler and
     * retained by the VM at run time, so they may be read reflectively.
     *
     * @see java.lang.reflect.AnnotatedElement
     */
    RUNTIME

3. 指定注解的作用目标@Target(ElementType.FIELD)

代码语言:javascript
复制
public enum ElementType {
    /** Class, interface (including annotation type), or enum 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,

    /**
     * Type parameter declaration
     *
     * @since 1.8
     */
    TYPE_PARAMETER,

    /**
     * Use of a type
     *
     * @since 1.8
     */
    TYPE_USE
}

自定义注解案例

代码语言:javascript
复制
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

// 自定义作用在Field上的注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface TestField
{
    String name();
}

// 自定义在method上的注解
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface TestAnnotation
{
    String name();
    int age() default 18;
    int[] score();
}

// 测试类

public class Test
{
    @TestAnnotation(name = "james", age =18 , score = {23,24})
    public void hello(){
        System.out.println("");
    }

    @TestField(name = "james")
    private String username;

    public static void main(String[] args) throws NoSuchMethodException, NoSuchFieldException 
    {
        // 通过反射来回去method 和 fields
        Method method = Test.class.getMethod("hello", null);
        Field[] fields = Test.class.getDeclaredFields();

        for (Field field: fields) {
            if (field.isAnnotationPresent(TestField.class)) {
                TestField annotation = field.getAnnotation(TestField.class);
                System.out.println("annotation.name() = " + annotation.name());
            }
        }
        if(method.isAnnotationPresent(TestAnnotation.class)){
            TestAnnotation tf =  method.getAnnotation(TestAnnotation.class);
            System.out.println("name: " + tf.name() +" age: "+ tf.age());
        }
    }
}

// 输出结果
annotation.name() = james
name: james age: 18

References

https://blog.csdn.net/wangpengzhi19891223/article/details/78131137

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Table of Contents
  • What is annotation?
  • How to customize the annotation?
    • steps to customize the annotation
      • 自定义注解案例
      • References
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档