Java 自定义注解示范

自定义一个注解@Test

package annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
//生命周期 运行时仍然要在
@Retention(RetentionPolicy.RUNTIME)
//目标位置,就是在哪些位置可以使用这个注解,FIELD是成员变量上面,METHOD是方法上面,TYPE是类上面
@Target({ElementType.FIELD,ElementType.METHOD,ElementType.TYPE})
public @interface Test {
    //修饰符 类型  属性名() default 默认值;
    //默认值可写可不写,但是没有默认值的属性那么使用注解的时候就必须赋值
    public String stuId() default "";
    public int[] scores() default {0,0,0,0};
    public String value() default "Test Default Value";
}

使用这个注解

有默认值的属性可以不再赋值,没有默认值的属性必须赋值
如果是value这个特殊属性,可以不写value="hello"直接用@Test(“hello”)

package annotation;

public class Main{
    @Test
    public void method(){
        System.out.println("i am a method");
    }
    @Test(value="hello")
    public void hello(){
        System.out.println("i am a method");
    }
}

测试代码

  • 利用反射判断是否存在这个注解,存在则获取这个注解,并拿到注解里面的值,打印出来
package annotation;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class AnnotationDemo {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException {
        Class cls = Class.forName("annotation.Main");
        Object instance = cls.newInstance();
        for (Method method : cls.getDeclaredMethods()){
            System.out.println("方法名:"+method.getName());
            System.out.println("执行方法:");
            method.invoke(instance);
            System.out.println("如果有@Test注解则打印出来");
            if (method.isAnnotationPresent(Test.class)){
                System.out.println("该方法存在@Test注解");
                Test annotation = method.getAnnotation(Test.class);
                System.out.println("获取注解里的值");
                System.out.println("@Test注解的value为:"+annotation.value());
            }
        }
    }
}

运行结果

在这里插入图片描述

spring运用注解

在使用spring或者springboot框架时我们也可以自己定义一些注解使用,比如计算每个函数执行用了多久

posted @ 2021-06-27 22:31  HumorChen99  阅读(0)  评论(0编辑  收藏  举报  来源