→阿童沐

財富==支撐一個人生存多長時間的能力!

导航

<Java注解> 模拟JUnit的注解实例=

主要代码:

package com.shengsiyuan.contest;

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

@Target(value = {ElementType.METHOD})
@Retention(value = RetentionPolicy.RUNTIME)
public @interface Test
{
}

 

package com.shengsiyuan.contest;

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

public class ApplicationRun
{
    public void run(String className)
    {
        try
        {
            Class<?> clazz = Class.forName(className);
            Object obj = clazz.newInstance();
            Method[] methods = clazz.getMethods();
            
            for (Method method : methods)
            {
                if(method.isAnnotationPresent(Test.class) && method.getGenericParameterTypes().length == 0)
                {
                    method.invoke(obj, new Object[0]);
                }
            }
        }
        catch (ClassNotFoundException e)
        {
            e.printStackTrace();
        }
        catch (InstantiationException e)
        {
            e.printStackTrace();
        }
        catch (IllegalAccessException e)
        {
            e.printStackTrace();
        }
        catch (IllegalArgumentException e)
        {
            e.printStackTrace();
        }
        catch (InvocationTargetException e)
        {
            e.printStackTrace();
        }
        
    }
}

 

测试:

package com.shengsiyuan.contest;

public class MyClass
{
    public void method1()
    {
        System.out.println("method1");
    }
    
    @Test
    public void method2()
    {
        System.out.println("method2");
    }
    @Test
    public int add(int a, int b)
    {
        return a + b;
    }
    
    @Test
    public void doSomething(String str)
    {
        System.out.println(str);
    }
    
    @Test
    public void doSomething2()
    {
        System.out.println("doSomething2()");
    }
}

 

package com.shengsiyuan.contest;

public class MTest
{
    public static void main(String[] args)
    {
        new ApplicationRun().run("com.shengsiyuan.contest.MyClass");
    }
}

 

执行结果如下:

 

 

 

 

 

 

 

posted on 2012-05-08 18:29  阿童沐  阅读(194)  评论(0)    收藏  举报