如何实现自定义注解

如题所述

首先,定义一个注解:

package com.guxiang.test;

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

首先自定义一个 myTest注解
/**
 * @author guxiang
 * @date 2016年12月24日 下午10:22:11
 * 自定义的myTest注解
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD,ElementType.ANNOTATION_TYPE})
public @interface MyTest {
    long time() default -1;
}

其次,写一个类用于被myTest注解,实现测试:

package com.guxiang.test;

public class SomeDaoImpl {
    public void save(){
        System.out.println("保存了数据");
    }
    public void update(){
        System.out.println("更新了数据");
    }
}

写一个测试类 这个类 引用myTest注解:

package com.guxiang.test;
public class SomeDaoImplTest {

    private SomeDaoImpl dao= new SomeDaoImpl();
    /**
     * 测试添加
     */
    @MyTest
    public void testAdd(){
        dao.save();
    }

    @MyTest
    public void testUpdate(){
        dao.update();
    }

最后,写一个myTestRunner类使用反射实现注解的功能:

package com.guxiang.test;

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



// 反射注解
public class MyTestRunner {
    public static void main(String[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException {
        Class clazz = SomeDaoImplTest.class;
        Method[] ms = clazz.getMethods();
        for (Method method : ms) {
            boolean hasMyTest = method.isAnnotationPresent(MyTest.class);
            if (hasMyTest) {
                method.invoke(clazz.newInstance(), null);
            }
        }
    }
}

温馨提示:答案为网友推荐,仅供参考
相似回答