汇道科技天瑞地安程序员

(003)java中的注解(Annotation)

2016-11-27  本文已影响1053人  林湾村龙猫

简介

注解,java中提供了一种原程序中的元素关联任何信息、任何元素的途径的途径和方法。

注解是那些插入到源代码中使用其他工具可以对其进行处理的标签。注解不会改变程序的编译方式。java编译器会对包含注解与不包含注解的代码生成相同的虚拟机指令。在java中,注解是被当做修饰符(如public/static之类)来使用的。

概览图:

java中的注解概览图

注解与注释

注释是供人看的,注解是供程序调用的。一种是程序员写给另一个程序员的,一种是程序员写给计算机解析的。

常用注解

注解运行机制分类

注解来源分类

元注解

给注解进行注解,用于自定义注解。

自定义注解

//@Target(ElementType.METHOD)
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Description {
    String desc() default "";
    String author() default "";
    int age() default 18;
}

使用注解

// @<注解名称>(<成员名1>=<成员值1>,<成员名2>=<成员值2> ...)

@Description(desc = "I'm class annotation")
public class AnnotationApp {

    @Description(desc = "I'm method annotation",author = "rudy")
    public String eyeColor(){
        return "red";
    }
}

解析注解

通过反射获取类、方法、成员上的运行时注解信息,从而实现动态控制程序运行的逻辑。

import Annotation.Description;
import org.junit.Test;

public class AnnotationTest {

    @Test
    public void testParse() throws ClassNotFoundException {
        // 取出注解
        Class cls = Class.forName("Annotation.AnnotationApp");
        boolean isExit =  cls.isAnnotationPresent(Description.class);
        if(isExit){
            // 做逻辑处理
            Description annotation = (Description) cls.getAnnotation(Description.class);
            System.out.println("get annotation:" + annotation.desc());
        }else{
            System.out.println("no annotation!");
        }
    }
}

他山之石

上一篇 下一篇

猜你喜欢

热点阅读