自定义注解是 Java 中的一个特性,可以用来给代码添加额外的元数据信息,从而实现更灵活的编程。

下面是一个自定义注解的案例,用来标记一个方法是否为测试方法:

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

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface TestMethod {

}

在上面的代码中,我们使用了@Retention注解来指定注解的保留策略为运行时保留,即在运行时可以通过反射获取到该注解。使用@Target注解来指定注解的作用目标为方法。

接下来我们可以在代码中使用这个自定义注解:

public class TestClass {

    @TestMethod
    public void testMethod1() {
        System.out.println('This is a test method 1.');
    }

    @TestMethod
    public void testMethod2() {
        System.out.println('This is a test method 2.');
    }

    public void normalMethod() {
        System.out.println('This is a normal method.');
    }

    public static void main(String[] args) {
        TestClass testClass = new TestClass();
        Method[] methods = testClass.getClass().getMethods();
        for (Method method : methods) {
            if (method.isAnnotationPresent(TestMethod.class)) {
                System.out.println('Found a test method: ' + method.getName());
            }
        }
    }
}

在上面的代码中,我们定义了一个TestClass类,其中有三个方法,其中两个方法使用了我们自定义的@TestMethod注解。

main方法中,我们使用反射获取到TestClass类的所有方法,然后判断每个方法是否有@TestMethod注解,如果有则打印出方法名。

运行上面的代码,输出如下:

Found a test method: testMethod1
Found a test method: testMethod2

可以看到,我们成功地通过自定义注解来标记了测试方法,并且在运行时能够获取到这些标记的方法。这样我们就可以使用自定义注解来实现一些自动化测试框架或者其他类似的功能。

Java 自定义注解实战:标记测试方法

原文地址: https://www.cveoy.top/t/topic/yaw 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录