一個簡單的自訂註解的實現

來源:互聯網
上載者:User

大家知道,在javaee各技術裡面,註解被廣泛的使用。那麼註解是如何?的呢。

額。。下面就給出一個本菜鳥 寫的一個 仿製 junit測試單元的一個 灰常簡單的myTest註解(本人學僧,第一次寫部落格,希望大家多提寶貴意見。。)

 /** *  */package com.guxiang.test;
 /** *  */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;/** * @author guxiang * @date 2016年12月24日 下午10:26:07 */// 反射註解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);            }        }    }}


這個測試類別仿製了 junit測試單元 
執行MyTestRunner 的main方法 後 會在控制台輸出以下

儲存了資料
更新了資料

於此就得到了 測試那個被測試類別的功能。。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.