自定义注解

自定义注解

package com.xxx.annotation;

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

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface AnnotationA {

    /**
     * varietyA
     *
     * @return
     */
    String memberA() default "value";
 
}

1. @interface:注解定义

2. @Target:限定自定义注解可以在哪些元素上使用

ElementType.TYPE

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

Class, interface (including annotation type), or enum declaration

ElementType.FIELD

用于描述域

Field declaration (includes enum constants)

3. @Retention:限定自定义注解的生命周期

RetentionPolicy.RUNTIME

运行期阶段

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.

RetentionPolicy.CLASS

编译到class文件阶段(默认)

Annotations are to be recorded in the class file by the compiler 

RetentionPolicy.SOURCE

JAVA源文件阶段

Annotations are to be discarded by the compiler.

3. 自定义注解中定义成员变量的规则:

  • 定义是以无形参的方法形式声明的
  • 注解方法不带参数
  • 注解方法返回值参数:基本类型、String、Enums、Annotation 以上及其数组类型
  • 注解方法可有默认值 default "value"

引用注解

package cn.xxx.dto;

import cn.xxx.annotation.AnnotationA;

public class DtoA {

    @ExampleA(memberA = "valueB")
    private String planName;
}

获取注解的值

package cn.superfw.biz.platform.poi.factory;

import cn.superfw.biz.platform.annotation.ExcelImportField;
import cn.superfw.biz.platform.poi.entity.ExcelEntity;
import cn.superfw.biz.platform.poi.entity.ExcelPropertyEntity;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class ExcelMappingFactory {
    public void getAnnotationValue(){
        Class classA = DtoA.class;
        // 获取类的所有域
        Field[] fields = classA.getDeclaredFields();
        for (Field field:fields){
            // 获取域的指定注解
            AnnotationA annotationA = field.getAnnotation(AnnotationA.class);
            if ( null != annotationA ){
               // 获取注解的值
               String memberValue = annotationA.memberA();
            }
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值