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…...
调用支付宝接口响应40004 SYSTEM_ERROR问题排查
在对接支付宝API的时候,遇到了一些问题,记录一下排查过程。 Body:{"datadigital_fincloud_generalsaas_face_certify_initialize_response":{"msg":"Business Failed","code":"40004","sub_msg…...
基于Uniapp开发HarmonyOS 5.0旅游应用技术实践
一、技术选型背景 1.跨平台优势 Uniapp采用Vue.js框架,支持"一次开发,多端部署",可同步生成HarmonyOS、iOS、Android等多平台应用。 2.鸿蒙特性融合 HarmonyOS 5.0的分布式能力与原子化服务,为旅游应用带来…...
新能源汽车智慧充电桩管理方案:新能源充电桩散热问题及消防安全监管方案
随着新能源汽车的快速普及,充电桩作为核心配套设施,其安全性与可靠性备受关注。然而,在高温、高负荷运行环境下,充电桩的散热问题与消防安全隐患日益凸显,成为制约行业发展的关键瓶颈。 如何通过智慧化管理手段优化散…...
【HarmonyOS 5 开发速记】如何获取用户信息(头像/昵称/手机号)
1.获取 authorizationCode: 2.利用 authorizationCode 获取 accessToken:文档中心 3.获取手机:文档中心 4.获取昵称头像:文档中心 首先创建 request 若要获取手机号,scope必填 phone,permissions 必填 …...
【VLNs篇】07:NavRL—在动态环境中学习安全飞行
项目内容论文标题NavRL: 在动态环境中学习安全飞行 (NavRL: Learning Safe Flight in Dynamic Environments)核心问题解决无人机在包含静态和动态障碍物的复杂环境中进行安全、高效自主导航的挑战,克服传统方法和现有强化学习方法的局限性。核心算法基于近端策略优化…...
Redis:现代应用开发的高效内存数据存储利器
一、Redis的起源与发展 Redis最初由意大利程序员Salvatore Sanfilippo在2009年开发,其初衷是为了满足他自己的一个项目需求,即需要一个高性能的键值存储系统来解决传统数据库在高并发场景下的性能瓶颈。随着项目的开源,Redis凭借其简单易用、…...
通过 Ansible 在 Windows 2022 上安装 IIS Web 服务器
拓扑结构 这是一个用于通过 Ansible 部署 IIS Web 服务器的实验室拓扑。 前提条件: 在被管理的节点上安装WinRm 准备一张自签名的证书 开放防火墙入站tcp 5985 5986端口 准备自签名证书 PS C:\Users\azureuser> $cert New-SelfSignedCertificate -DnsName &…...
抽象类和接口(全)
一、抽象类 1.概念:如果⼀个类中没有包含⾜够的信息来描绘⼀个具体的对象,这样的类就是抽象类。 像是没有实际⼯作的⽅法,我们可以把它设计成⼀个抽象⽅法,包含抽象⽅法的类我们称为抽象类。 2.语法 在Java中,⼀个类如果被 abs…...
Unity中的transform.up
2025年6月8日,周日下午 在Unity中,transform.up是Transform组件的一个属性,表示游戏对象在世界空间中的“上”方向(Y轴正方向),且会随对象旋转动态变化。以下是关键点解析: 基本定义 transfor…...
RushDB开源程序 是现代应用程序和 AI 的即时数据库。建立在 Neo4j 之上
一、软件介绍 文末提供程序和源码下载 RushDB 改变了您处理图形数据的方式 — 不需要 Schema,不需要复杂的查询,只需推送数据即可。 二、Key Features ✨ 主要特点 Instant Setup: Be productive in seconds, not days 即时设置 :在几秒钟…...
