本文使用了反射,反射的话有不理解可以百度问问度娘.
注解以前一直觉得很难,主要不知道注解怎么使用的,今天看了一本书之后有了灵感
注解其实很简单 就像是一个标识一样
定义注解
@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");
}
}
}
}
}