注解的应用-用在方法上进行标记--通过标记来识别处理某些方法

自定义注解:

/*先自己定义1个注解,这个注解运行时能获得信息,修饰方法
 * 
 * 
 * 
 * */

package day8yue31;

import java.lang.*;
import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Testable {

}

在方法上标记注解:

/*
 * 测试类
 * 
 * */

package day8yue31;

public class MyTest {
	@Testable()
	public void method1()
	{
		System.out.println("method1");
	}
	
	public void method2()
	{
		System.out.println("method2");
	}
	@Testable()
	public void method3()
	{
		System.out.println("method3");
	}
	public void method4()
	{
		System.out.println("method4");
		
	}
	
	@Testable()
	public void method5()
	{
		System.out.println("method5");
	}
	@Testable()
	public void method6()
	{
		System.out.println("method6");
	}
	@Testable()
	public void method7()
	{
		System.out.println("method");
	}

}

通过标记处理对应的方法:

/*  处理类
 * 
 * */

package day8yue31;

import java.lang.reflect.Method;

public class ProcessorTest {
	//处理方法,按照标记来执行对应的方法
	public static void process(String classname) throws Exception
	{
		int passed = 0;
		int failed = 0;
		
		//遍历classname对应的类里面所有方法
		
		for(Method m : Class.forName(classname).getMethods())
		{
			 if(m.isAnnotationPresent(Testable.class))
			 {
				 try {
					 m.invoke(null);
					 passed++;
					
				} catch (Exception e) {
					System.out.println("方法"+m+"运行失败");
					failed++;
				}
				 
			 }
		}
		
		System.out.println("一共运行了"+(failed+passed)+"个方法");
		System.out.println("失败了"+(failed)+"个方法");
		System.out.println("成功了"+(passed)+"个方法");
	}
	
	public static void main(String[] arga) throws Exception
	{
		process("day8yue31.MyTest");
		
	}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值