【Java开发】自定义注解RuntimeTest

下文三个步骤创建的文件目录结构参考:
在这里插入图片描述

1.新增注解文件RuntimeTest

package xyz.dongzhensong.junitlearn.test;

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

@Retention(value= RetentionPolicy.RUNTIME)
public @interface RuntimeTest {

}

@Retention(value=RetentionPolicy.RUNTIME)
方法内传入的value是一个枚举,该枚举共有三个值:

  • RetentionPolicy.SOURCE: 源文件阶段
  • RetentionPolicy.CLASS: 字节码阶段
  • RetentionPolicy.RUNTIME: 运行阶段(创建对象阶段)

注意:@Retention注解是用于定义 新增的自定义注解 存在的阶段,默认为源文件阶段(即RetentionPolicy.SOURCE)
对应于上述三个阶段,获取类的方式也有三种:

  • 源代码阶段:以.java结尾的文件的形式存在
    通过Class.forName(“类名”)方法获得
  • 字节码阶段:将字节码文件编译后以.class结尾的文件存在
    通过类名.class方式获取
  • 创建对象阶段:JVM将字节码文件加载进内存的方法区内
    通过对象.getClass方法获得

延伸阅读:https://blog.csdn.net/Chicbrother/article/details/78463260

2.新建测试类 RuntimeTestAnnotionTest

用于测试自定义的注解

package xyz.dongzhensong.junitlearn.test;


public class RuntimeTestAnnotionTest {

    public void testMethod1(){
        System.out.println("RuntimeTestAnnotionTest.testMethod1");
    }

    @RuntimeTest
    public void testMethod2(){
        System.out.println("RuntimeTestAnnotionTest.testMethod2");
    }

    @RuntimeTest
    public void testMethod3(){
        System.out.println("RuntimeTestAnnotionTest.testMethod3");
    }

}

注意:方法2与3使用了自定义的注解 @RuntimeTest

3.用途分析:自定义注解运行类RuntimeTestRunner

package xyz.dongzhensong.junitlearn.test;

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

public class RuntimeTestRunner {
    public static void main(String[] args)
            throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException {
        // 1.获取测试类的Class
        Class clazz = RuntimeTestAnnotionTest.class;
        // 2.获取对应Class中的所有的方法(测试的方法必须是public)
        Method[] methods = clazz.getMethods();
        // 3.遍历获取的方法
        for(Method method:methods){
            boolean flag = method.isAnnotationPresent(RuntimeTest.class);
            if(flag){
                // RuntimeTest注解的方法:
                method.invoke(clazz.newInstance(), null);
            }else{
                System.out.println("非RuntimeTest注解的方法:"+method.getName());
            }
        }
    }
}

boolean isAnnotationPresent(Class<? extends Annotation> annotationClass):
判断当前方法是否存在指定类型的注解:true-存在,false-不存在。

运行main方法后可看到结果:

非自定义注解的方法:testMethod1
RuntimeTestAnnotionTest.testMethod2
RuntimeTestAnnotionTest.testMethod3
非自定义注解的方法:wait
非自定义注解的方法:wait
非自定义注解的方法:wait
非自定义注解的方法:equals
非自定义注解的方法:toString
非自定义注解的方法:hashCode
非自定义注解的方法:getClass
非自定义注解的方法:notify
非自定义注解的方法:notifyAll

由打印结果可分析到:通过自定义注解可以动态获取加注解的方法,从而在单元测试过程中个性化的执行特定的测试方法。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值