本文使用了反射,反射的话有不理解能够百度问问度娘.git
注解之前一直以为很难,主要不知道注解怎么使用的,今天看了一本书以后有了灵感github
定义注解
@Retention(RetentionPolicy.RUNTIME)//保留期限 @Target(ElementType.METHOD)//使用注解的目标类型 public [@interface](https://my.oschina.net/u/996807) NeedTest {//定义注解 boolean value() default true;//声明注解成员 }
使用注解
public class ForumService { @NeedTest(value=true) public void deleteForum(int id){ System.out.println("value=true"); } @NeedTest(value=false) public void deleteTopic(int id){ System.out.println("value=false"); } }
利用反射给注解赋予功能
public class TestAnnotation { public static void main(String[] args) { Class clazz=ForumService.class;//获得class对象 Method[] methods=clazz.getDeclaredMethods(); System.out.println(methods.length); for (Method method : methods) { NeedTest nt=method.getAnnotation(NeedTest.class); if(nt!=null){ if(nt.value()){ System.out.println(method.getName()+"() need to be Tested"); }else{ System.out.println(method.getName()+"() need not to be Tested"); } } } } }