Java注解

annotation提供了四种元注解:

@Documented -- 注解是否将包含在javadoc中

@Retention --什么时候使用该注解

@Target 注解用于什么地方

@Inherited 是否允许资料基础该注解

 

RetentionPolicy.SOURCE 在编译阶段丢弃,不会写入字节码

RetentionPolicy.CLASS 在类加载时丢弃 注解默认使用这种

RetentionPolicy.RUNTIME 始终不会丢弃,运行期也保留该注解,因此可以使用反射机制读取该注解的信息,自定义注解时常采用此种方式

@Target :

ElementType.TYPE 

ElementType.FIELD 

ElementType.METHOD

ElementType.PARAMETER

ElementType.CONSTRUCTOR

ElementType.LOCAL_VARIABLE

ElementType.ANNOTATION_TYPE

ElementType.PACKAGE

 

Annotations只支持基本类型、string及枚举类型。注解种的缩影的舒心被定义成发放,并允许提供默认值

@Target(ElementType.METHOD)

@Retention(RetentionPolicy.RUNTIME)

@interface Todo{

  public enum Priority {LOW,HIGH}

  public enum Status {YES, NO}

  String author() default "Tim";

  Priority pririty() default Priority.LOW;

  Status status() default Status.NO;

}

@Todo(priority = Todo.Priority.MEDIUM, author = "yes", status = Todo.Status.NO)

public void incompleteMethod1(){

}

 

如果注解只有一个属性,可以直接命名value

@interface Author{

  String value();

}

 

@Author("123")

public void someMethod(){}

 

通过使用反射机制自定义注解逻辑,现通过一个小示例

1、自定义注解

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Compont {

    String identifier() default "";
}

 

2、应用自定义注解

@Compont(identifier="123")
public class UpperCase {

    String toUpperCase(String str) {
        if(null != str) {
            return str.toUpperCase();
        }
        return null;
    }
}

 

3、 处理自定义注解

public class AnnotationMain {

    public static void main(String[] args) throws Exception{
        
        Class<?> clzss = Class.forName("com.java.annotation.UpperCase");
        boolean annotationBoolean = clzss.isAnnotationPresent(Compont.class);
        if(annotationBoolean) {
            Compont compont = (Compont)clzss.getAnnotation(Compont.class);
            String annotationResult = compont.identifier();
            System.out.println(String.format("compont annotaion return result: %s", annotationResult));
        }
    }
}

 

 

posted @ 2018-01-27 20:55  秋水秋色  阅读(172)  评论(0编辑  收藏  举报