java注解原理

注解的基本概念和原理

注解(Annotation)提供了一种安全的类似注释的机制,为我们在代码中添加信息,提供了一种形式化的方法,使我们可以在稍后某个时刻方便的使用这些数据(通过解析注解来使用这些数据)。

 

元注解是java API提供,是专门用来定义注解的注解。

四个元注解分别是:@Target,@Retention,@Documented,@Inherited 

 

实现注解需要三个条件:

注解声明使用注解的元素注解解释器

 

注解声明

package com.test;

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

/**
 * 注解声明 自定义注解,用来配置方法
 * 
 * @author 窗外赏雪
 */
@Retention(RetentionPolicy.RUNTIME)
// 表示注解在运行时依然存在
@Target(ElementType.METHOD)
// 表示注解可以被使用于方法上
public @interface CustomAnnotation {

    String paramValue() default "窗外赏雪"; // 表示我的注解需要一个参数 名为"paramValue" 默认值为"johness"
}

 

使用注解的元素

package com.test;

/**
 * 使用注解的元素
 * 
 * @author 窗外赏雪
 */
public class UseAnnotation {

    // 普通的方法
    public void SayHelloNormal(String name) {
        System.out.println("Hello, " + name);
    }

    // 使用注解并传入参数的方法
    @CustomAnnotation(paramValue = "李白")
    public void SayHello(String name) {
        System.out.println("Hello, " + name);
    }

    // 使用注解并使用默认参数的方法
    @CustomAnnotation
    public void SayHelloDefault(String name) {
        System.out.println("Hello, " + name);
    }
}

 

注解解释器

package com.test;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 注解解释器
 * 
 * @author 窗外赏雪
 */
public class AnnotionInterpreter {

    public AnnotionInterpreter() throws IllegalAccessException, IllegalArgumentException, InvocationTargetException{
        UseAnnotation element = new UseAnnotation(); // 初始化一个实例,用于方法调用
        Method[] methods = UseAnnotation.class.getDeclaredMethods(); // 获得所有方法

        for (Method method : methods) {
            CustomAnnotation annotationTmp = null;
            if ((annotationTmp = method.getAnnotation(CustomAnnotation.class)) != null) // 检测是否使用了我们的注解
            method.invoke(element, annotationTmp.paramValue()); // 如果使用了我们的注解,我们就把注解里的"paramValue"参数值作为方法参数来调用方法
            else method.invoke(element, "杜甫"); // 如果没有使用我们的注解,我们就需要使用普通的方式来调用方法了
        }
    }

}

 

测试

package com.test;

import java.lang.reflect.InvocationTargetException;

public class Test {

    public static void main(String[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
            new AnnotionInterpreter();
        
    }
}

 

你可能感兴趣的:(java注解原理)