java注解使用其实很简单

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

因此说注解没啥,主要是标识咱们的代码,赋值也只是为了标识而已,源码下载地址:源码下载 github

相关文章
相关标签/搜索