当前位置: 代码网 > it编程>编程语言>Java > Java注解示例详解(含底层原理)

Java注解示例详解(含底层原理)

2025年10月10日 Java 我要评论
一、什么是注解?定义注解:注解是java语言的元数据(在java层面,所有代码都可视为数据,而注解就是为代码添加特定数据的机制),用于修饰代码元素(类、方法、字段等)。它本身不直接影响程序运行,需要通

一、什么是注解?

定义注解:注解是java语言的元数据(在java层面,所有代码都可视为数据,而注解就是为代码添加特定数据的机制),用于修饰代码元素(类、方法、字段等)。它本身不直接影响程序运行,需要通过工具(编译器、运行时环境、反射api)解析处理,实现编译检查、代码生成、运行时配置等功能。

注解的价值:简化传统的xml配置方式、减少模板代码、提高代码可读性、实现逻辑与配置解耦

与注释的区别:

  • 替代传统xml配置方式
  • 减少重复代码
  • 提升代码可读性
  • 实现逻辑与配置分离
维度注解(annotation)注释(comment)
作用对象程序(编译器、框架可解析)开发者(仅用于阅读)
语法规范有严格的语法(需用@interface定义)无语法限制(// 或 /* */包裹)
运行时影响可通过反射api获取,影响程序逻辑编译时被忽略,无任何影响

注解的本质:注解的本质实际上是一个继承自 java.lang.annotation.annotation 的接口

注解的处理时机:

  • 编译期间:编译器根据注解处理器(一个继承了 javax.annotation.processing.abstractprocessor 抽象类的类,该类由 javac 编译器进行读取),可以在编译期间对注解进行处理(代码生成)
  • 运行期间:通过反射机制获取注解(此时 jvm 用动态代理为该注解生成了一个的代理类),可以在运行是获取注解的信息

二、标记注解的注解——元注解

元注解本质上是给 java 工具链(编译器、jvm)“看” 的规则说明,用于告诉这些工具:“这个注解应该被如何处理?它能修饰什么?能保留到什么时候”。

java 定义了 5 个标准的元注解类型且都位于 java.lang.annotation 包下:

@target

用于指定注解可以应用的java元素类型,例如类、方法、字段,属性的值由枚举类 java.lang.annotation.elementtype 提供:

字段说明
type用于类、接口、注解、枚举
field用于字段(类的成员变量),或者枚举常量
method用于方法
parameter用于方法或者构造方法的参数
constructor用于构造方法
local_variable用于变量
annotation_type用于注解
package用于包
type_parameter用于泛型参数
type_use用于声明语句、泛型或者强制转换语句中的类型
module用于模块

@retention

用于指定注解的保留策略,即注解在哪个阶段保留,属性的值由枚举类 java.lang.annotation.retentionpolicy 提供:

字段说明
source会被编译器丢弃,不会出现在class文件中。
class默认值,会被保留在class文件中,但 jvm 加载类时不会处理它们。
runtime会被保留在class文件中,还会被jvm加载,因此可以通过反射机制在运行时访问。这也是注解生命周期中最常用的一种策略

@documented

用于标注其他注解,使其在生成 javadoc 文档时被包含在内。

@inherited

用于标注其他注解,被标记的注解具有继承性。

当被标记的注解用在一个类上,那么该类的子类可以继承这个被标记的注解。

注意:@inherited 仅对类级别的注解有效,对方法、字段、参数等其他程序元素的注解无继承效果。

示例:

@target({elementtype.type, elementtype.method, elementtype.field})
@retention(retentionpolicy.runtime)
@documented
@inherited // 仅对类上的注解有效,方法和字段上的该注解不会被继承
public @interface myannotation { ... }

@repeatable

用于标记一个注解可以在同一个程序元素上重复使用。

使用时需要指定一个 “容器注解”(该容器注解的属性是当前注解的数组)。

示例:

// 容器注解
@target(elementtype.type)
@retention(retentionpolicy.runtime)
public @interface myannotations {
    myannotation[] value();
}

// 重复注解(使用@repeatable标记)
@repeatable(myannotations.class)
@target(elementtype.type)
@retention(retentionpolicy.runtime)
public @interface myannotation {
    string value();
}

// 使用示例
@myannotation("a")
@myannotation("b")
public class myclass {}

三、自定义注解

定义注解,使用 @interface 关键字,基本结构:

import java.lang.annotation.*;

// 元注解:指定注解的适用范围(类、方法、字段等)
@target({elementtype.type, elementtype.method, elementtype.field})
// 元注解:指定注解的生命周期(source/class/runtime)
@retention(retentionpolicy.runtime)
// 元注解:是否被javadoc文档提取
@documented
// 元注解:是否允许子类继承该注解(仅对类注解有效)
@inherited
public @interface myannotation {
    // 注解属性(类似接口方法,但可指定默认值)
    string value(); // 必选属性(无默认值)
    int count() default 1; // 可选属性(有默认值)
    string[] tags() default {}; // 数组类型
}

注解属性的类型限制:

  • 基本数据类型
  • string、class、枚举
  • 其他注解
  • 以上类型的数组
  • 如果使用其他类型,编译时会直接报错

"value" 属性的特殊性:

当注解有且仅有`value`一个属性时,使用时可省略属性名

// 定义仅含value属性的注解
public @interface myannot {
    string value();
}

// 使用时可简化
@myannot("test")  // 等价于 @myannot(value = "test")
public class demo {}

当注解有多个属性,但仅需指定`value`时,仍可省略属性名

public @interface myannot {
    string value();
    int count() default 1; // 有默认值
}

// 仅指定value,可省略属性名
@myannot("test")  // 等价于 @myannot(value = "test", count = 1)
public class demo {}

若需指定多个属性,`value`不能省略属性名

public @interface myannot {
    string value();
    int count() default 1;
}

// 错误写法:多属性时不能省略value=
// @myannot("test", count = 2) 

// 正确写法:必须显式指定value=
@myannot(value = "test", count = 2)
public class demo {}

四、反射 api 获取注解信息

4.1 可访问注解信息的核心类

说明
java.lang.class表示类、接口、枚举等类型,可访问类本身、父类、实现接口上的注解。
java.lang.reflect.field表示类的字段,可访问字段上的注解。
java.lang.reflect.method表示类的方法,可访问方法本身、方法参数、方法返回值上的注解。
java.lang.reflect.constructor表示类的构造函数,可访问构造函数本身及参数上的注解。
java.lang.reflect.parameter表示方法或构造函数的参数,可访问参数上的注解。
java.lang.reflect.annotatedtype

表示被注解的类型(如泛型类型、数组类型等)。

4.2 反射 api 中获取注解的核心方法

4.2.1 class 类的注解方法

方法说明
getannotation(class<t> annotationclass)获取该类上指定类型的注解(若注解被@inherited元注解标记,则包括从父类继承的注解),不存在则返回null
getannotations()获取该类上的所有注解(包括继承的)。
getdeclaredannotation(class<t> annotationclass)获取该类上直接声明的指定类型注解(不包括继承的)。
getdeclaredannotations()获取该类上直接声明的所有注解(不包括继承的)。
isannotationpresent(class<? extends annotation> annotationclass)判断该类是否存在指定类型的注解(包括继承的)。

4.2.2 field 类的注解方法

方法说明
getannotation(class<t> annotationclass)获取该字段上指定类型的注解。
getannotations()获取该字段上的所有注解。
getdeclaredannotations()获取该字段上直接声明的所有注解(因字段注解不可继承,故结果与getannotations()一致)。
isannotationpresent(class<? extends annotation> annotationclass)判断该字段是否存在指定类型的注解。

4.2.3 method 类的注解方法

方法说明
getannotation(class<t> annotationclass)获取该方法上指定类型的注解。
getannotations()获取该方法上的所有注解。
getdeclaredannotations()getannotations()(方法注解不可继承)。
isannotationpresent(class<? extends annotation> annotationclass)判断该方法是否存在指定类型的注解。
getparameterannotations()获取该方法所有参数上的注解(返回二维数组,每个元素是一个参数的注解数组)。
getannotationsbytype(class<t> annotationclass)获取该方法上指定类型的所有注解(支持重复注解)。

4.2.4 constructor 类的注解方法

方法说明
getannotation(class<t> annotationclass)获取该构造函数上指定类型的注解。
getannotations()获取该构造函数上的所有注解。
getdeclaredannotations()getannotations()(构造函数注解不可继承)。
getparameterannotations()获取该构造函数所有参数上的注解(返回二维数组)。

4.2.4 parameter 类的注解方法

方法说明
getannotation(class<t> annotationclass)获取该参数上指定类型的注解。
getannotations()获取该参数上的所有注解。
getdeclaredannotations()getannotations()(参数注解不可继承)。
isannotationpresent(class<? extends annotation> annotationclass)判断该参数是否存在指定类型的注解。

4.2.5 annotatedtype 类的注解方法

方法说明
getannotation(class<t> annotationclass)获取指定类型的注解(若存在)。
getannotations()返回该类型上的所有注解(包括继承的)。
getdeclaredannotations()返回该类型上直接声明的注解(不包括继承的)。
getannotationsbytype(class<t> annotationclass)获取指定类型的所有注解(包括重复注解)。
type gettype()返回当前 annotatedtype 所表示的原始类型(如 list<string> 对应的 type 对象)。

五、代码示例

自定义日志注解,用于标记需要记录日志的方法

import java.lang.annotation.*;

/**
 * 自定义日志注解
 * 用于标记需要记录日志的方法
 */
@target(elementtype.method) // 仅用于方法
@retention(retentionpolicy.runtime) // 运行时保留,可通过反射获取
@documented // 生成文档时包含该注解
public @interface log {
    // 操作描述(value属性,可简化使用)
    string value() default "";
    
    // 是否记录参数
    boolean recordparams() default true;
    
    // 是否记录返回值
    boolean recordresult() default false;
}

运行时注解解析器,通过动态代理实现日志记录功能

import java.lang.reflect.invocationhandler;
import java.lang.reflect.method;
import java.lang.reflect.proxy;
import java.util.arrays;

/**
 * 运行时注解解析器
 * 通过动态代理实现日志记录功能
 */
public class logruntimeparser implements invocationhandler {
    
    // 目标对象
    private final object target;
    
    public logruntimeparser(object target) {
        this.target = target;
    }
    
    // 创建代理对象
    public static object createproxy(object target) {
        return proxy.newproxyinstance(
            target.getclass().getclassloader(),
            target.getclass().getinterfaces(),
            new logruntimeparser(target)
        );
    }
    
    @override
    public object invoke(object proxy, method method, object[] args) throws throwable {
        // 检查方法是否有@log注解
        if (method.isannotationpresent(log.class)) {
            log log = method.getannotation(log.class);
            
            // 记录开始时间
            long starttime = system.currenttimemillis();
            
            // 打印日志信息
            system.out.println("\n===== 日志开始 =====");
            system.out.println("操作描述: " + log.value());
            system.out.println("方法名称: " + method.getname());
            
            // 如果需要记录参数
            if (log.recordparams() && args != null) {
                system.out.println("参数列表: " + arrays.tostring(args));
            }
            
            // 执行目标方法
            object result = method.invoke(target, args);
            
            // 如果需要记录返回值
            if (log.recordresult()) {
                system.out.println("返回结果: " + result);
            }
            
            // 记录执行时间
            system.out.println("执行时间: " + (system.currenttimemillis() - starttime) + "ms");
            system.out.println("===== 日志结束 =====");
            
            return result;
        }
        
        // 没有@log注解的方法,直接执行
        return method.invoke(target, args);
    }
}

用户服务接口,用于动态代理

/**
 * 用户服务接口,用于动态代理
 */
public interface userserviceinterface {
    boolean login(string username, string password);
    string register(string username, string email);
    void updateprofile(string username, string newemail);
}

业务服务类,使用自定义的@log注解

/**
 * 业务服务类,使用自定义的@log注解
 */
public class userservice {
    
    // 使用注解,仅指定value(可简化写法)
    @log("用户登录")
    public boolean login(string username, string password) {
        system.out.println("执行登录逻辑...");
        return "admin".equals(username) && "123456".equals(password);
    }
    
    // 完整指定注解的所有属性
    @log(value = "用户注册", recordparams = true, recordresult = true)
    public string register(string username, string email) {
        system.out.println("执行注册逻辑...");
        return "注册成功,用户id: " + system.currenttimemillis();
    }
    
    // 不使用注解的方法(不会被日志记录)
    public void updateprofile(string username, string newemail) {
        system.out.println("执行更新资料逻辑...");
    }
}

测试主类

/**
 * 测试主类
 */
public class main {
    public static void main(string[] args) {
        // 创建目标对象
        userservice userservice = new userservice();
        
        // 创建代理对象(用于运行时解析注解)
        userserviceinterface proxy = (userserviceinterface) logruntimeparser.createproxy(userservice);
        
        // 调用被@log注解的方法
        proxy.login("admin", "123456");
        proxy.register("testuser", "test@example.com");
        
        // 调用未被@log注解的方法
        proxy.updateprofile("admin", "new@example.com");
    }
}

六、底层原理

编译时处理注解的过程:

编译时处理注解实际上是通过一个实现了 javax.annotation.processing.abstractprocessor 抽象类的类来进行处理的,具体的操作可以参考网址:

java注解处理器实战 | desperado

运行时处理注解的过程:

先来看一段代码,一段自定义的注解源代码,注解当中包含一个 value() 属性。代码如下:

import java.lang.annotation.elementtype;
import java.lang.annotation.retention;
import java.lang.annotation.retentionpolicy;
import java.lang.annotation.target;

/**
 * @author nanji
 * @version 1.0
 * @annotationname initmethod
 * @desc 自定义的初始化方法注解
 * @date 2025/8/2: 11:20
 */
@target(elementtype.method)
@retention(retentionpolicy.runtime)
public @interface initmethod {
    string value() default "";
}

经过java编译器编译之后的代码,再反编译回来是什么样子呢?代码如下:

// 编译后的 initmethod.class
public interface initmethod extends java.lang.annotation.annotation {
     public abstract string value(); // 对应注解的value属性
    
    // 编译器自动添加:返回注解类型
    class<? extends annotation> annotationtype();
}

可以看到,定义的 initmethod 注解实际上是一个继承了 java.lang.annotation.annotation 接口的接口。接下来我们来看一下运行时访问注解发生了什么?

目录结构如下:

同样以 initmethod 为例:

import java.lang.annotation.elementtype;
import java.lang.annotation.retention;
import java.lang.annotation.retentionpolicy;
import java.lang.annotation.target;

/**
 * @author nanji
 * @version 1.0
 * @annotationname initmethod
 * @desc 自定义的初始化方法注解
 * @date 2025/8/2: 11:20
 */
@target(elementtype.method)
@retention(retentionpolicy.runtime)
public @interface initmethod {
    string value() default "";
}

在定义一个 initdemo 类,用来测试 initmethod 注解,代码如下:

/**
 * @author nanji
 * @version 1.0
 * @classname initdemo
 * @desc 测试初始化方法注解
 * @date 2025/8/2 : 11:23
 */
public class initdemo {
    @initmethod("init...")
    public void init() {
        system.out.println("正在初始化...");
    }
}

接着定义一个测试类 main,代码如下:

import java.lang.reflect.*;

/**
 * @author nanji
 * @version 1.0
 * @classname main
 * @desc 测试类
 * @date 2025/8/2: 11:30
 */
public class main {
    public static void main(string[] args) throws exception {
        // 写入代理类文件
        system.setproperty("jdk.proxy.proxygenerator.savegeneratedfiles", "true");
        class<initdemo> cls = initdemo.class;
        // 获取 initdemo 类的所有方法
        method[] methods = cls.getmethods();
        // 遍历所有方法
        for (method method : methods) {
            // 判断方法是否有 initmethod 注解
            boolean isinitmethod = method.isannotationpresent(initmethod.class);
            // 如果有 initmethod 注解,则获取当前的注解代理类
            if (isinitmethod) {
                // 获取 initmethod 注解的代理类
                initmethod initmethod = method.getannotation(initmethod.class);
                // 获取代理类的类实例
                system.out.println(initmethod.getclass());
                // 获取注解的值,实际上是通过代理类调用了注解的 value() 方法
                string value = initmethod.value();
                // 打印注解的 value() 方法的值
                system.out.println("initmethod value: " + value);
                // 调用 initdemo 类的 init() 方法
                method.invoke(cls.getconstructor().newinstance());
            }
        }
    }
}

现在我们来运行一下这段程序,看看使用 initmethod 这个注解发生了什么

可以看到控制台打印了三条语句:

第一条 class jdk.proxy2.$proxy1 实际上就是生成的代理类。

第二条 initmethod value: init... 实际上是通过代理类调用了 initmethod 注解类的 value() 方法。

第三条 正在初始化... 实际上是通过反射调用了 initdemo 类的 init() 方法。

那生成的代理类在哪里呢?类中的内容又有什么呢?接着往下看:

在运行测试类的 main 方法时,方法中的第一行代码:

// 写入代理类文件
system.setproperty("jdk.proxy.proxygenerator.savegeneratedfiles", "true");

这行代码的作用就是允许代理类的class文件写入你的磁盘当中,默认是写入到你的项目模块中,会生成如下目录:

接着我们打开 jdk 目录下最后面的 proxy2 目录下的 $proxy1 类,通过idea打开后查看类中的结构:

package jdk.proxy2;

import com.ktjiaoyu.annotation.demo.init.initmethod;
import java.lang.invoke.methodhandles;
import java.lang.reflect.invocationhandler;
import java.lang.reflect.method;
import java.lang.reflect.proxy;
import java.lang.reflect.undeclaredthrowableexception;

public final class $proxy1 extends proxy implements initmethod {
    private static final method m0;
    private static final method m1;
    private static final method m2;
    private static final method m3;
    private static final method m4;

    public $proxy1(invocationhandler var1) {
        super(var1);
    }

    public final int hashcode() {
        try {
            return (integer)super.h.invoke(this, m0, (object[])null);
        } catch (runtimeexception | error var2) {
            throw var2;
        } catch (throwable var3) {
            throw new undeclaredthrowableexception(var3);
        }
    }

    public final boolean equals(object var1) {
        try {
            return (boolean)super.h.invoke(this, m1, new object[]{var1});
        } catch (runtimeexception | error var2) {
            throw var2;
        } catch (throwable var3) {
            throw new undeclaredthrowableexception(var3);
        }
    }

    public final string tostring() {
        try {
            return (string)super.h.invoke(this, m2, (object[])null);
        } catch (runtimeexception | error var2) {
            throw var2;
        } catch (throwable var3) {
            throw new undeclaredthrowableexception(var3);
        }
    }

    public final string value() {
        try {
            return (string)super.h.invoke(this, m3, (object[])null);
        } catch (runtimeexception | error var2) {
            throw var2;
        } catch (throwable var3) {
            throw new undeclaredthrowableexception(var3);
        }
    }

    public final class annotationtype() {
        try {
            return (class)super.h.invoke(this, m4, (object[])null);
        } catch (runtimeexception | error var2) {
            throw var2;
        } catch (throwable var3) {
            throw new undeclaredthrowableexception(var3);
        }
    }

    static {
        try {
            m0 = class.forname("java.lang.object").getmethod("hashcode");
            m1 = class.forname("java.lang.object").getmethod("equals", class.forname("java.lang.object"));
            m2 = class.forname("java.lang.object").getmethod("tostring");
            m3 = class.forname("com.ktjiaoyu.annotation.demo.init.initmethod").getmethod("value");
            m4 = class.forname("com.ktjiaoyu.annotation.demo.init.initmethod").getmethod("annotationtype");
        } catch (nosuchmethodexception var2) {
            throw new nosuchmethoderror(((throwable)var2).getmessage());
        } catch (classnotfoundexception var3) {
            throw new noclassdeffounderror(((throwable)var3).getmessage());
        }
    }

    private static methodhandles.lookup proxyclasslookup(methodhandles.lookup var0) throws illegalaccessexception {
        if (var0.lookupclass() == proxy.class && var0.hasfullprivilegeaccess()) {
            return methodhandles.lookup();
        } else {
            throw new illegalaccessexception(var0.tostring());
        }
    }
}

这个类是通过反射 api 获取注解时由jvm实现的,在这个类的静态代码块中为成员变量 m3 附了值,这个值实际上就是 initmethod 注解中的 value() 方法。

static {
        try {
            m0 = class.forname("java.lang.object").getmethod("hashcode");
            m1 = class.forname("java.lang.object").getmethod("equals", class.forname("java.lang.object"));
            m2 = class.forname("java.lang.object").getmethod("tostring");
            m3 = class.forname("com.ktjiaoyu.annotation.demo.init.initmethod").getmethod("value");
            m4 = class.forname("com.ktjiaoyu.annotation.demo.init.initmethod").getmethod("annotationtype");
        } catch (nosuchmethodexception var2) {
            throw new nosuchmethoderror(((throwable)var2).getmessage());
        } catch (classnotfoundexception var3) {
            throw new noclassdeffounderror(((throwable)var3).getmessage());
        }
    }

在我们调用 value() 方法时,实际上是调用的代理类中的 value() 方法,代码如下:

public final string value() {
        try {
            return (string)super.h.invoke(this, m3, (object[])null);
        } catch (runtimeexception | error var2) {
            throw var2;
        } catch (throwable var3) {
            throw new undeclaredthrowableexception(var3);
        }
    }

这个 value() 方法就是获取注解 value 属性的值。到这里就清楚了,为什么可以通过反射去拿到注解的值。

七、总结

  1. 注解的作用是用来描述和标记java代码当中的元素(类、方法、字段等)
  2. 元注解是用来标记注解的注解,作用是给 java 工具链(编译器、jvm、注解处理器)去识别的规则,java 工具链根据对应的规则进行对应的处理
  3. 注解的本质实际上是一个实现了 java.lang.annotation.annotation 接口的接口
  4. 注解的处理时机发生在编译期,由一个实现了 javax.annotation.processing.abstractprocessor 抽象类的类来进行操作
  5. 注解的处理时机发生在运行期,通过java动态代理,去实现注解当中定义的方法,从而获取对应的值
  6. 通过 system.setproperty("jdk.proxy.proxygenerator.savegeneratedfiles", "true") 方法,设置jvm的系统属性,告诉jvm将生成的动态代理类保存到文件系统中,方便开发者查看和调试。

到此这篇关于java注解详解的文章就介绍到这了,更多相关java注解详解内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com