本文使用了反射,反射的話有不理解能夠百度問問度娘.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"); } } } } }