Java自定义注解以及模拟单元测试

一、自定义注解

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...");
	}
	
}

你可能感兴趣的:(java)