Java自定義註解以及模擬單元測試
阿新 • • 發佈:2019-01-31
一、自定義註解
1.編寫自定義註解類 @MyTest
package com.itheima.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ElementType.METHOD,ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface MyAnno { //註解的屬性 String name(); int age() default 28; }
2.編寫目標類
package com.itheima.annotation;
@MyAnno(name = "zhangsan")
public class MyAnnoTest {
@SuppressWarnings("all")
@MyAnno(name = "zhangsan")
//@MyAnno({ "aaa","bbb","ccc"})
public void show(String str){
System.out.println("show running...");
}
}
3.編寫測試方法
package com.itheima.annotation; import java.lang.reflect.Method; public class MyAnnoParser { public static void main(String[] args) throws NoSuchMethodException, SecurityException { //解析show方法上面的@MyAnno //直接的目的是 獲得show方法上的@MyAnno中的引數 //獲得show方法的位元組碼物件 Class clazz = MyAnnoTest.class; Method method = clazz.getMethod("show", String.class); //獲得show方法上的@MyAnno MyAnno annotation = method.getAnnotation(MyAnno.class); //獲得@MyAnno上的屬性值 System.out.println(annotation.name());//zhangsan System.out.println(annotation.age());//28 //根據業務需求寫邏輯程式碼 } }
二、模擬單元測試
1.編寫MyTest類
package com.itheima.case1; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface MyTest { //不需要屬性 }
2.編寫MyTestParster類
package com.itheima.case1;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class MyTestParster {
public static void main(String[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException {
//獲得TestDemo
Class clazz = TestDemo.class;
//獲得所有的方法
Method[] methods = clazz.getMethods();
if(methods!=null){
//獲得註解使用了@MyTest的方法
for(Method method:methods){
//判斷該方法是否使用了@MyTest註解
boolean annotationPresent = method.isAnnotationPresent(MyTest.class);
if(annotationPresent){
//該方法使用MyTest註解了
method.invoke(clazz.newInstance(), null);
}
}
}
}
}
3.編寫TestDemo類
package com.itheima.case1;
import org.junit.Test;
public class TestDemo {
//程式設計師開發中測試用的
@Test
public void test1(){
System.out.println("test1 running...");
}
@MyTest
public void test2(){
System.out.println("test2 running...");
}
@MyTest
public void test3(){
System.out.println("test3 running...");
}
}