JAVA 注解-学习篇(2)

本文内容承接Java 注解-学习篇(1)http://www.javashuo.com/article/p-ejgfioln-y.htmljava

自定义注解

  1. 声明 @interface用来声明一个注解,即在声明一个类时,把class变成@interface。就能成功声明一个注解了。
  2. 参数 其中的每个方法其实是声明了一个配置参数。方法的名称就是参数的名称,返回值类型就是参数的类型(返回值类型只能是基本类型、Class、String、enum)。能够经过default来声明参数的默认值。
  3. 调用 根据元注解规定的范围,使用@注解名(参数列表)调用。
  4. 应用场景 要用好注解,必须熟悉java 的反射机制,注解的解析彻底依赖于反射

第一个注解

这是一个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

  1. 只有一个参数时,能够在调用时不使用参数名。
  2. 参数有default值时,能够在调用时不出如今参数列表中。下面的案例中id列表是能够不填写的。
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

未完待续!!虚拟机

相关文章
相关标签/搜索