Java 自定义注解例子

来源:互联网 发布:ubuntu 漏洞提权 编辑:程序博客网 时间:2024/06/05 12:04

在这篇文章中,我将展示怎么创建两个自定义的注解-@Test和TestInfo,来模拟一件的单元测试的框架

补充:这个单元测试的例子是受官方文档的启发。这篇。

@Test注解

这个@interface标志Java这是一个自定义的标签,然后你可以在方法上像@Test(enable=false)这样添加注解

package com.mkyong.test.core;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 Test {//should ignore this test?public boolean enabled() default true;}

注意:方法的声明不能有任何参数或者抛出异常,返回值的类型要限制在原始值,String、Class、enums、annotations和数组类型

@TesterInfo注解

这个@TesterInfo是应用在类层面上的,存储测试类的细节,这展示了enum、array和String不同返回值的用法
package com.mkyong.test.core;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.TYPE) //类级别public @interface TesterInfo {public enum Priority {   LOW, MEDIUM, HIGH}Priority priority() default Priority.MEDIUM;String[] tags() default "";String createdBy() default "Mkyong";String lastModified() default "03/01/2014";}

单元测试的例子

创建一个单元测试的例子,使用新自定义的注解@Test和@TesterInfo注解这个例子
package com.mkyong.test;import com.mkyong.test.core.Test;import com.mkyong.test.core.TesterInfo;import com.mkyong.test.core.TesterInfo.Priority;@TesterInfo(priority = Priority.HIGH, createdBy = "mkyong.com",  tags = {"sales","test" })public class TestExample {@Testvoid testA() {  if (true)throw new RuntimeException("This test always failed");}@Test(enabled = false)void testB() {  if (false)throw new RuntimeException("This test always passed");}@Test(enabled = true)void testC() {  if (10 > 1) {// do nothing, this test always passed.  }}}

Java反射,读取这个注解

下边这个例子展示怎么使用Java反射读取和处理自定义的注解
package com.mkyong.test;import java.lang.annotation.Annotation;import java.lang.reflect.Method;import com.mkyong.test.core.Test;import com.mkyong.test.core.TesterInfo;public class RunTest {  public static void main(String[] args) throws Exception {System.out.println("Testing...");int passed = 0, failed = 0, count = 0, ignore = 0;Class<TestExample> obj = TestExample.class;// Process @TesterInfoif (obj.isAnnotationPresent(TesterInfo.class)) {Annotation annotation = obj.getAnnotation(TesterInfo.class);TesterInfo testerInfo = (TesterInfo) annotation;System.out.printf("%nPriority :%s", testerInfo.priority());System.out.printf("%nCreatedBy :%s", testerInfo.createdBy());System.out.printf("%nTags :");int tagLength = testerInfo.tags().length;for (String tag : testerInfo.tags()) {if (tagLength > 1) {System.out.print(tag + ", ");} else {System.out.print(tag);}tagLength--;}System.out.printf("%nLastModified :%s%n%n", testerInfo.lastModified());}// Process @Testfor (Method method : obj.getDeclaredMethods()) {// if method is annotated with @Testif (method.isAnnotationPresent(Test.class)) {Annotation annotation = method.getAnnotation(Test.class);Test test = (Test) annotation;// if enabled = true (default)if (test.enabled()) {  try {method.invoke(obj.newInstance());System.out.printf("%s - Test '%s' - passed %n", ++count, method.getName());passed++;  } catch (Throwable ex) {System.out.printf("%s - Test '%s' - failed: %s %n", ++count, method.getName(), ex.getCause());failed++;  }} else {System.out.printf("%s - Test '%s' - ignored%n", ++count, method.getName());ignore++;}}}System.out.printf("%nResult : Total : %d, Passed: %d, Failed %d, Ignore %d%n", count, passed, failed, ignore);}}

输出结果:
Testing...Priority :HIGHCreatedBy :mkyong.comTags :sales, testLastModified :03/01/20141 - Test 'testA' - failed: java.lang.RuntimeException: This test always failed 2 - Test 'testC' - passed 3 - Test 'testB' - ignoredResult : Total : 3, Passed: 1, Failed 1, Ignore 1


0 0