首页  

自定义注解实例     所属分类 java 浏览量 1148
定义注解

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{
	boolean ignore() default false;
}

@Target  注解应用目标,类 方法 方法参数等
@Retention 注解要保留到什么时候  源码 class文件  或者是运行时





在方法上使用注解

import java.util.Date;

public class Hello{
	
	@Test
	public void hello1(){
		System.out.println("hello1() run,"+new Date());
	}
	
	@Test(ignore=true)
	public void hello2(){
		System.out.println("hello2() run,"+new Date());
	}
	
}


使用注解 
通过反射获取方法上的注解


import java.lang.reflect.Method;

public class TestMain{
	
	public static void main(String[] args) throws Exception {
		Hello hello = new Hello();
		run(hello);
		
	}
	
	private static void run(Object obj)throws Exception{
		Method[] methods = obj.getClass().getDeclaredMethods();	
		Test test = null;
		for(Method method:methods){
			test = method.getAnnotation(Test.class);
			if(test!=null && !test.ignore()){
				method.invoke(obj);
			}
		}			
	}

}

上一篇     下一篇
为什么开发一个操作系统那么难

AQS同步队列与条件队列

公平锁与非公平锁的关键区别

springboot应用jar包冲突解决实例

eclipse中分析pom文件

maven依赖排除