【java】 --- java自定义注解

7 篇文章 0 订阅

我们最常使用的注解是@Override,他的源码如下

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}

从其源码我们可以看到

1.自定义注解一般用@interface表示

2.其上一般有@Target 和  @Retention

 

@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)         // 包

@Documented:表示注解包含在javadoc中

@Inherited:表示注解可以被继承

 

例如自定义实现一个@Autowired注解,如下

package com.derry.annotation;

import java.lang.annotation.*;

/**
 * @Author:derry
 * @Description:
 * @Date: Created in 11:09 2019/2/19
 * @Modified By:
 */
@Target({ElementType.PARAMETER,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Autowired {
    String value() default "";
}
使用该注解
package com.derry.test;

import com.derry.annotation.Autowired;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author:derry
 * @Description:
 * @Date: Created in 11:09 2019/2/19
 * @Modified By:
 */
public class Test {
    @Autowired("derry")
    private static String name;
    @Autowired("男")
    private static String sex;

    public static void print(){
        System.out.println("该用户为:"+name+"     性别为:"+sex);
    }
    public static void initAnnotation() {
            Class<?> clazz = Test.class;
            Field[] fields = clazz.getDeclaredFields();
            for (Field field:fields
                 ) {
                if (!field.isAnnotationPresent(Autowired.class)){
                    continue;
                }else{
                    Autowired autowired = field.getAnnotation(Autowired.class);
                    Object value = autowired.value();
                    if(field.getName().equals("name")){
                        name = (String) value;
                    }
                    if (field.getName().equals("sex")){
                        sex = (String) value;
                    }
                }

            }
    }

    public static void main(String[] args) {
        //初始化加载注解
        initAnnotation();
        print();
    }
}

输出结果为:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值