自定义注解定义与使用

欢迎点击

入门

1. 定义

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

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
    String value() default "defaultValue";
}

@Target: 指定注解的使用范围; ElementType 枚举 TYPE, FIELD,METHOD…

@Retention: 指示带注释类型的注释将保留多长时间。默认: @Retention 上的 @Retention(RetentionPolicy.RUNTIME); RetentionPolicy 枚举 CLASS\RUNTIME\SOURCE

2. 使用

import com.yang.annotation.MyAnnotation;

@MyAnnotation("value")
public class Entity() {
}

3. 获取注解内容

通过反射获取注解内变量的值

import com.yang.annotation.MyAnnotation;

import javax.swing.text.html.parser.Entity;

public class Test {
    void content() {
        System.out.println(Entity.class.getAnnotation(MyAnnotation.class).value());
    }
}
获取注解的方法

对应 ElementType的 TYPE\FIELD\METHOD

  1. TYPE (Class 类下)

getAnnotation(Class annotationClass) - 获取指定类型的注解 , 无返回 null
getAnnotations() - 返回所有注解
getAnnotationsByType(Class annotationClass)
Returns annotations that are associated with this element.

  1. Field

getAnnotatedType()
Returns an AnnotatedType object that represents the use of a type to specify the declared type of the field represented by this Field.
getAnnotation(Class annotationClass)
Returns this element’s annotation for the specified type if such an annotation is present, else null.
getAnnotationsByType(Class annotationClass)
Returns annotations that are associated with this element.

  1. METHOD

getAnnotatedReturnType()
Returns an AnnotatedType object that represents the use of a type to specify the return type of the method/constructor represented by this Executable.
getAnnotation(Class annotationClass)
Returns this element’s annotation for the specified type if such an annotation is present, else null.
getDeclaredAnnotations() - 返回元素注解列表
Returns annotations that are directly present on this element.

4. 输出内容

value
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值