Java注解的原理
目录
问题:
作用:
原理:
注解的限制
拓展:
问题:
今天刷面经,发现自己不懂注解的原理,特此记录。
作用:
注解的作用主要是给编译器看的,让它帮忙生成一些代码,或者是帮忙检查、判断和校验数据。
1.给编译器看:
- 帮助编译器进行语法检查(如 @Override、@Deprecated)。
- 通过注解处处理器生成代(如Lombok的@Getter,@Setter)。
2.给运行时框架看
- 通过反射机制动态读取注解信息,实现功能增强(如依赖注入、AOP、配置管理、数据验证)等。
原理:
注解的本质一个特殊的接口,继承了java.lang.annotation.Annotation
接口。当定义一个注解时,Java 编译器会将其转换为一个实现了 Annotation
接口的代理类。
import java.lang.annotation.*;@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation {String value() default "defaultValue";int priority() default 1;
}//伪代码
public interface MyAnnotation extends Annotation {String value(); // 对应注解中的 value 属性int priority(); // 对应注解中的 priority 属性
}//验证
@Retention(RetentionPolicy.RUNTIME) 可以通过反射机制拿去值public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchFieldException, NoSuchMethodException, InvocationTargetException, UnknownHostException {//获取目标类Class<Student> studentClass = Student.class;//判断类有没有注解if(studentClass.isAnnotationPresent(MyAnnotation.class)){//拿到代理对象MyAnnotation annotation = studentClass.getAnnotation(MyAnnotation.class);System.out.println("value:"+annotation.value());System.out.println("priotity:"+annotation.priority());}}
注解的限制
虽然注解看起来像普通的接口,但它们有一些特殊的限制:
- 不能继承其他接口 :注解不能继承其他接口(除了隐式的
Annotation
接口)。public @interface MyAnnotation extends SomeOtherInterface {} // 错误!
- 不能包含方法体 :注解中的方法只能声明,不能有实现。
public @interface MyAnnotation { String value() { return "defaultValue"; } // 错误! }
- 不支持泛型 :注解中的方法不能使用泛型。
public @interface MyAnnotation { List<String> values(); // 正确 List<T> values(); // 错误! }

拓展:
java.lang.annotation.Annotation
是所有注解的父接口。它定义了一些通用的方法,用于处理注解的元数据。
package java.lang.annotation;/*** The common interface extended by all annotation interfaces. Note that an* interface that manually extends this one does <i>not</i> define* an annotation interface. Also note that this interface does not itself* define an annotation interface.** More information about annotation interfaces can be found in section* {@jls 9.6} of <cite>The Java Language Specification</cite>.** The {@link java.lang.reflect.AnnotatedElement} interface discusses* compatibility concerns when evolving an annotation interface from being* non-repeatable to being repeatable.** @author Josh Bloch* @since 1.5*/
/*** 所有注解接口继承的公共接口。注意:手动扩展此接口的接口<i>不会</i>成为注解接口。* 此接口自身也不作为注解接口。* * 更多注解接口的详细信息,请参阅《Java语言规范》第{@jls 9.6}节。* * 当注解接口从不可重复变为可重复时,{@link java.lang.reflect.AnnotatedElement}* 接口讨论了相关的兼容性问题。* * 作者:Josh Bloch* 自版本:1.5*/
public interface Annotation {
public interface Annotation {/*** Returns true if the specified object represents an annotation* that is logically equivalent to this one. In other words,* returns true if the specified object is an instance of the same* annotation interface as this instance, all of whose members are equal* to the corresponding member of this annotation, as defined below:* <ul>* <li>Two corresponding primitive typed members whose values are* {@code x} and {@code y} are considered equal if {@code x == y},* unless their type is {@code float} or {@code double}.** <li>Two corresponding {@code float} members whose values* are {@code x} and {@code y} are considered equal if* {@code Float.valueOf(x).equals(Float.valueOf(y))}.* (Unlike the {@code ==} operator, NaN is considered equal* to itself, and {@code 0.0f} unequal to {@code -0.0f}.)** <li>Two corresponding {@code double} members whose values* are {@code x} and {@code y} are considered equal if* {@code Double.valueOf(x).equals(Double.valueOf(y))}.* (Unlike the {@code ==} operator, NaN is considered equal* to itself, and {@code 0.0} unequal to {@code -0.0}.)** <li>Two corresponding {@code String}, {@code Class}, enum, or* annotation typed members whose values are {@code x} and {@code y}* are considered equal if {@code x.equals(y)}. (Note that this* definition is recursive for annotation typed members.)** <li>Two corresponding array typed members {@code x} and {@code y}* are considered equal if {@code Arrays.equals(x, y)}, for the* appropriate overloading of {@link java.util.Arrays#equals Arrays.equals}.* </ul>** @return true if the specified object represents an annotation* that is logically equivalent to this one, otherwise false*/boolean equals(Object obj);/*** Returns the hash code of this annotation.** <p>The hash code of an annotation is the sum of the hash codes* of its members (including those with default values).** The hash code of an annotation member is (127 times the hash code* of the member-name as computed by {@link String#hashCode()}) XOR* the hash code of the member-value.* The hash code of a member-value depends on its type as defined below:* <ul>* <li>The hash code of a primitive value <i>{@code v}</i> is equal to* <code><i>WrapperType</i>.valueOf(<i>v</i>).hashCode()</code>, where* <i>{@code WrapperType}</i> is the wrapper type corresponding* to the primitive type of <i>{@code v}</i> ({@link Byte},* {@link Character}, {@link Double}, {@link Float}, {@link Integer},* {@link Long}, {@link Short}, or {@link Boolean}).** <li>The hash code of a string, enum, class, or annotation member-value* <i>{@code v}</i> is computed as by calling* <code><i>v</i>.hashCode()</code>. (In the case of annotation* member values, this is a recursive definition.)** <li>The hash code of an array member-value is computed by calling* the appropriate overloading of* {@link java.util.Arrays#hashCode(long[]) Arrays.hashCode}* on the value. (There is one overloading for each primitive* type, and one for object reference types.)* </ul>** @return the hash code of this annotation*/int hashCode();/*** Returns a string representation of this annotation. The details* of the representation are implementation-dependent, but the following* may be regarded as typical:* <pre>* @com.example.Name(first="Duke", middle="of", last="Java")* </pre>** @return a string representation of this annotation*/String toString();/*** Returns the annotation interface of this annotation.** @apiNote Implementation-dependent classes are used to provide* the implementations of annotations. Therefore, calling {@link* Object#getClass getClass} on an annotation will return an* implementation-dependent class. In contrast, this method will* reliably return the annotation interface of the annotation.** @return the annotation interface of this annotation* @see Enum#getDeclaringClass*/Class<? extends Annotation> annotationType();
}
相关文章:

Java注解的原理
目录 问题: 作用: 原理: 注解的限制 拓展: 问题: 今天刷面经,发现自己不懂注解的原理,特此记录。 作用: 注解的作用主要是给编译器看的,让它帮忙生成一些代码,或者是帮忙检查…...
AI知识架构之神经网络
神经网络:这是整个内容的主题,是一种模拟人类大脑神经元结构和功能的计算模型,在人工智能领域广泛应用。基本概念:介绍神经网络相关的基础概念,为后续深入理解神经网络做铺垫。定义与起源: 神经网络是模拟人类大脑神经元结构和功能的计算模型,其起源于对生物神经系统的研…...

OpenGL 04--GLSL、数据类型、Uniform、着色器类
一、着色器 在 OpenGL 中,着色器(Shader)是运行在 GPU 上的程序,用于处理图形渲染管线中的不同阶段。 这些小程序为图形渲染管线的某个特定部分而运行。从基本意义上来说,着色器只是一种把输入转化为输出的程序。着色器…...
学习笔记06——JVM调优
JVM 调优实战:性能优化的技巧与实战 在 Java 开发中,JVM(Java Virtual Machine)作为 Java 程序的运行环境,其性能直接影响到应用程序的响应速度和吞吐量。合理的 JVM 调优可以显著提升应用性能,降低延迟&a…...
深度学习(3)-TensorFlow入门(常数张量和变量)
低阶张量操作是所有现代机器学习的底层架构,可以转化为TensorFlow API。 张量,包括存储神经网络状态的特殊张量(变量)。 张量运算,比如加法、relu、matmul。 反向传播,一种计算数学表达式梯度的方法&…...
3-2 WPS JS宏 工作簿的打开与保存(模板批量另存为工作)学习笔记
************************************************************************************************************** 点击进入 -我要自学网-国内领先的专业视频教程学习网站 *******************************************************************************************…...
【GO】学习笔记
目录 学习链接 开发环境 开发工具 GVM - GO多版本部署 GOPATH 与 go.mod go常用命令 环境初始化 编译与运行 GDB -- GNU 调试器 基本语法与字符类型 关键字与标识符 格式化占位符 基本语法 初始值&零值&默认值 变量声明与赋值 _ 下划线的用法 字…...
【TypeScript】ts在vue中的使用
目录 一、Vue 3 TypeScript 1. 项目创建与配置 项目创建 关键配置文件 2.完整项目结构示例 3. 组件 Props 类型定义 4. 响应式数据与 Ref 5. Composition 函数复用 二、组件开发 1.组合式API(Composition API) 2.选项式API(Options…...

2025前端框架最新组件解析与实战技巧:Vue与React的革新之路
作者:飞天大河豚 引言 2025年的前端开发领域,Vue与React依然是开发者最青睐的框架。随着Vue 3的全面普及和React 18的持续优化,两大框架在组件化开发、性能优化、工程化支持等方面均有显著突破。本文将从最新组件特性、使用场景和编码技巧三…...
Elasticsearch 的分布式架构原理:通俗易懂版
Elasticsearch 的分布式架构原理:通俗易懂版 Lucene 和 Elasticsearch 的前世今生 Lucene 是一个功能强大的搜索库,提供了高效的全文检索能力。然而,直接基于 Lucene 开发非常复杂,即使是简单的功能也需要编写大量的 Java 代码&…...

【DeepSeek】【GPT-Academic】:DeepSeek集成到GPT-Academic(官方+第三方)
目录 1 官方deepseek 1.1 拉取学术GPT项目 1.2 安装依赖 1.3 修改配置文件中的DEEPSEEK_API_KEY 2 第三方API 2.1 修改DEEPSEEK_API_KEY 2.2 修改CUSTOM_API_KEY_PATTERM 2.3 地址重定向 2.4 修改模型参数 2.5 成功调用 2.6 尝试添加一个deepseek-r1参数 3 使用千帆…...

2.部署kafka:9092
官方文档:http://kafka.apache.org/documentation.html (虽然kafka中集成了zookeeper,但还是建议使用独立的zk集群) Kafka3台集群搭建环境: 操作系统: centos7 防火墙:全关 3台zookeeper集群内的机器,1台logstash 软件版本: …...

学习路之PHP --TP6异步执行功能 (无需安装任何框架)
学习路之PHP --异步执行功能 (无需安装任何框架) 简介一、工具类二、调用三、异步任务的操作四、效果: 简介 执行异步任务是一种很常见的需求,如批量发邮箱,短信等等执行耗时任务时,需要程序异步执行&…...
Uniapp 小程序复制、粘贴功能实现
在开发 Uniapp 小程序的过程中,复制和粘贴功能是非常实用且常见的交互需求。今天,我就来和大家详细分享如何在 Uniapp 中实现这两个功能。 复制功能:uni.setClipboardData方法 goResult() {uni.setClipboardData({data: this.copyContent, /…...

seacmsv9注入管理员账号密码+orderby+limit
一、seacmsv9 SQL注入漏洞 查看源码 <?php session_start(); require_once("include/common.php"); //前置跳转start $cs$_SERVER["REQUEST_URI"]; if($GLOBALS[cfg_mskin]3 AND $GLOBALS[isMobile]1){header("location:$cfg_mhost$cs");}…...

多通道数据采集和信号生成的模块化仪器如何重构飞机电子可靠性测试体系?
飞机的核心电子系统包括发电与配电系统,飞机内部所有设备和系统之间的内部数据通信系统,以及用于外部通信的射频设备。其他所有航空电子元件都依赖这些关键总线进行电力传输或数据通信。在本文中,我们将了解模块化仪器(无论是PCIe…...

天润融通分析DeepSeek如何一键完成从PR接入,到真正的业务接入
DeepSeek出圈之后,市场上很快掀起了一波DeepSeek接入潮。 在客户服务领域,许多企业见识到DeepSeek的超强能力后,也迅速接入DeepSeek并获得了不错的效果。 比如在客户接待服务场景,有企业将DeepSeek应用到智能问答助手࿰…...

免费PDF工具
Smallpdf.com - A Free Solution to all your PDF Problems Smallpdf - the platform that makes it super easy to convert and edit all your PDF files. Solving all your PDF problems in one place - and yes, free. https://smallpdf.com/#rappSmallpdf.com-解决您所有PD…...

PyTorch 源码学习:GPU 内存管理之它山之石——TensorFlow BFC 算法
TensorFlow 和 PyTorch 都是常用的深度学习框架,各自有一套独特但又相似的 GPU 内存管理机制(BFC 算法)。它山之石可以攻玉。了解 TensorFlow 的 BFC 算法有助于学习 PyTorch 管理 GPU 内存的精妙之处。本文重点关注 TensorFlow BFC 算法的核…...
【学写LibreCAD】1 LibreCAD主程序
一、源码 头文件: #ifndef MAIN_H #define MAIN_H#include<QStringList>#define STR(x) #x #define XSTR(x) STR(x)/*** brief handleArgs* param argc cli argument counter from main()* param argv cli arguments from main()* param argClean a list…...
在HarmonyOS ArkTS ArkUI-X 5.0及以上版本中,手势开发全攻略:
在 HarmonyOS 应用开发中,手势交互是连接用户与设备的核心纽带。ArkTS 框架提供了丰富的手势处理能力,既支持点击、长按、拖拽等基础单一手势的精细控制,也能通过多种绑定策略解决父子组件的手势竞争问题。本文将结合官方开发文档,…...

全球首个30米分辨率湿地数据集(2000—2022)
数据简介 今天我们分享的数据是全球30米分辨率湿地数据集,包含8种湿地亚类,该数据以0.5X0.5的瓦片存储,我们整理了所有属于中国的瓦片名称与其对应省份,方便大家研究使用。 该数据集作为全球首个30米分辨率、覆盖2000–2022年时间…...

华为OD机试-食堂供餐-二分法
import java.util.Arrays; import java.util.Scanner;public class DemoTest3 {public static void main(String[] args) {Scanner in new Scanner(System.in);// 注意 hasNext 和 hasNextLine 的区别while (in.hasNextLine()) { // 注意 while 处理多个 caseint a in.nextIn…...
GitHub 趋势日报 (2025年06月08日)
📊 由 TrendForge 系统生成 | 🌐 https://trendforge.devlive.org/ 🌐 本日报中的项目描述已自动翻译为中文 📈 今日获星趋势图 今日获星趋势图 884 cognee 566 dify 414 HumanSystemOptimization 414 omni-tools 321 note-gen …...

selenium学习实战【Python爬虫】
selenium学习实战【Python爬虫】 文章目录 selenium学习实战【Python爬虫】一、声明二、学习目标三、安装依赖3.1 安装selenium库3.2 安装浏览器驱动3.2.1 查看Edge版本3.2.2 驱动安装 四、代码讲解4.1 配置浏览器4.2 加载更多4.3 寻找内容4.4 完整代码 五、报告文件爬取5.1 提…...
在Ubuntu24上采用Wine打开SourceInsight
1. 安装wine sudo apt install wine 2. 安装32位库支持,SourceInsight是32位程序 sudo dpkg --add-architecture i386 sudo apt update sudo apt install wine32:i386 3. 验证安装 wine --version 4. 安装必要的字体和库(解决显示问题) sudo apt install fonts-wqy…...

短视频矩阵系统文案创作功能开发实践,定制化开发
在短视频行业迅猛发展的当下,企业和个人创作者为了扩大影响力、提升传播效果,纷纷采用短视频矩阵运营策略,同时管理多个平台、多个账号的内容发布。然而,频繁的文案创作需求让运营者疲于应对,如何高效产出高质量文案成…...
LangChain知识库管理后端接口:数据库操作详解—— 构建本地知识库系统的基础《二》
这段 Python 代码是一个完整的 知识库数据库操作模块,用于对本地知识库系统中的知识库进行增删改查(CRUD)操作。它基于 SQLAlchemy ORM 框架 和一个自定义的装饰器 with_session 实现数据库会话管理。 📘 一、整体功能概述 该模块…...

C/C++ 中附加包含目录、附加库目录与附加依赖项详解
在 C/C 编程的编译和链接过程中,附加包含目录、附加库目录和附加依赖项是三个至关重要的设置,它们相互配合,确保程序能够正确引用外部资源并顺利构建。虽然在学习过程中,这些概念容易让人混淆,但深入理解它们的作用和联…...
【JavaSE】多线程基础学习笔记
多线程基础 -线程相关概念 程序(Program) 是为完成特定任务、用某种语言编写的一组指令的集合简单的说:就是我们写的代码 进程 进程是指运行中的程序,比如我们使用QQ,就启动了一个进程,操作系统就会为该进程分配内存…...