本文内容承接Java 注解-学习篇(1)http://www.javashuo.com/article/p-ejgfioln-y.htmljava
这是一个Marker annotation(类体里面没有成员)测试注解。学习
package anotations; /** * 自定义注解 * Created by Administrator on 2016/11/26. */ public @interface Controller { }
注解的调用,由于没有规定范围测试
package controller; import anotations.Controller; /** * Created by Administrator on 2016/11/26. */ @Controller//在类前面 public class ControllerDemo { @Controller//在属性前面 private String str; @Controller//在方法前面 public void say(){ System.out.println("hello world"); } }
###使用元注解修饰 主要使用@Retention、@Target元注解修饰,元注解说明参考http://www.javashuo.com/article/p-ejgfioln-y.html 。下面案例注解能够在虚拟机中运行,这个主要方便测试,以及解析。.net
import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 自定义注解 * Created by Administrator on 2016/11/26. */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) public @interface Controller { }
###注解参数 注解中声明参数,返回值类型只能是基本类型、Class、String、enumcode
package anotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 自定义注解 * Created by Administrator on 2016/11/26. */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE}) public @interface Controller { String str(); int id() default 0; Class<Long> gid(); }
调用有参数的注解须要注意;blog
package controller; import anotations.Controller; /** * Created by Administrator on 2016/11/26. */ @Controller(str="test",id=1,gid=Long.class)//在类前面 public class ControllerDemo { private String str; public void say(){ System.out.println("hello world"); } }
还有最重要的一步,咱们学习注解,就是为了解析注解,这是最为核心的一步。请看下一个章节。get
未完待续!!虚拟机