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());}}

注解的限制

虽然注解看起来像普通的接口,但它们有一些特殊的限制:

  1. 不能继承其他接口 :注解不能继承其他接口(除了隐式的 Annotation 接口)。
    public @interface MyAnnotation extends SomeOtherInterface {} // 错误!
  2. 不能包含方法体 :注解中的方法只能声明,不能有实现。
    public @interface MyAnnotation {
    String value() { return "defaultValue"; } // 错误!
    }

  3. 不支持泛型 :注解中的方法不能使用泛型。
    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>*   &#064;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();
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/24636.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

seacmsv9注入管理员账号密码+orderby+limit

seacmsv9注入管理员账号密码 安装海洋CMS&#xff08;seacms&#xff09; 将upload文件夹里的文件全部上传至网页服务器后&#xff0c;执行以下操作: 请运行http://域名/install/index.php进行程序安装 SQL语句尝试注入 http://127.0.0.1/upload/comment/api/index.php?g…

【构建工具】Gradle Kotlin DSL中的大小写陷阱:BuildConfigField

在Android开发当中&#xff0c;BuildConfig是一个非常有用的功能&#xff0c;它允许我们在构建过程中定义常量&#xff0c;并在运行时使用它们。But&#xff01;&#xff01;当我们从传统的Groovy DSL迁移到Kotlin DSL时或者被Android Studio坑的时候&#xff0c;有一些细微的差…

AI如何改变传统工厂的生产模式?

随着第四次工业革命的浪潮席卷全球&#xff0c;制造业的数字化转型成为企业在竞争中脱颖而出的关键。过去&#xff0c;传统制造业往往依赖于大量的人工操作和低效率的管理流程&#xff0c;而如今&#xff0c;智能化、自动化、数据化已经成为未来制造业的必由之路。从车间到云端…

Redis

redis启动命令 默认端口启动redis&#xff1a; redis-server redis.windows.conf 指定端口9001和9002启动redis(需要新建配置文件&#xff0c;并修改配置文件port属性)&#xff1a; redis-server .\redis-9001.conf redis-server .\redis-9002.conf 检查是否启动Redis &#…

洛谷 P8705:[蓝桥杯 2020 省 B1] 填空题之“试题 E :矩阵” ← 卡特兰数

【题目来源】 https://www.luogu.com.cn/problem/P8705 【题目描述】 把 1∼2020 放在 21010 的矩阵里。要求同一行中右边的比左边大&#xff0c;同一列中下边的比上边的大。一共有多少种方案? 答案很大&#xff0c;你只需要给出方案数除以 2020 的余数即可。 【答案提交】 …

ARM 处理器平台 eMMC Flash 存储磨损测试示例

By Toradex秦海 1). 简介 目前工业嵌入式 ARM 平台最常用的存储器件就是 eMMC Nand Flash 存储&#xff0c;而由于工业设备一般生命周期都比较长&#xff0c;eMMC 存储器件的磨损寿命对于整个设备来说至关重要&#xff0c;因此本文就基于 NXP i.MX8M Mini ARM 处理器平台演示…

14.二叉搜索树

二叉搜索树 1.概念 ⼆叉搜索树⼜称⼆叉排序树&#xff0c;它或者是⼀棵空树&#xff0c;或者是具有以下性质的⼆叉树: *若它的左⼦树不为空&#xff0c;则左⼦树上所有结点的值都⼩于等于根结点的值 *若它的右⼦树不为空&#xff0c;则右⼦树上所有结点的值都⼤于等于根结点…

8、HTTP/1.0和HTTP/1.1的区别【高频】

第一个是 长连接&#xff1a; HTTP/1.0 默认 短连接&#xff0c;&#xff08;它也可以指定 Connection 首部字段的值为 Keep-Alive实现 长连接&#xff09;而HTTP/1.1 默认支持 长连接&#xff0c;HTTP/1.1是基于 TCP/IP协议的&#xff0c;创建一个TCP连接是需要经过三次握手的…

【爬虫基础】第二部分 爬虫基础理论 P1/3

上节内容回顾&#xff1a;【爬虫基础】第一部分 网络通讯 P1/3-CSDN博客 【爬虫基础】第一部分 网络通讯-Socket套接字 P2/3-CSDN博客 【爬虫基础】第一部分 网络通讯-编程 P3/3-CSDN博客 爬虫相关文档&#xff0c;希望互相学习&#xff0c;共同进步 风123456789&#xff…

nss刷题5(misc)

[HUBUCTF 2022 新生赛]最简单的misc 打开后是一张图片&#xff0c;没有其他东西&#xff0c;分离不出来&#xff0c;看看lsb&#xff0c;红绿蓝都是0&#xff0c;看到头是png&#xff0c;重新保存为png&#xff0c;得到一张二维码 扫码得到flag [羊城杯 2021]签到题 是个动图…

清华大学DeepSeek文档下载,清华大学deepseek下载(完成版下载)

文章目录 前言一、清华大学DeepSeek使用手册下载二、清华大学DeepSeek使用手册思维导图 前言 这是一篇关于清华大学deepseek使用手册pdf的介绍性文章&#xff0c;主要介绍了DeepSeek的定义、功能、使用方法以及如何通过提示语设计优化AI性能。以下是对这些核心内容的简要概述&…

强化学习演进:GRPO 从何而来

强化学习&#xff08;Reinforcement Learning, RL&#xff09;是机器学习的一个分支&#xff0c;其核心是让智能体&#xff08;Agent&#xff09;通过与环境&#xff08;Environment&#xff09;的交互&#xff0c;学习如何采取最优行动&#xff08;Action&#xff09;以最大化…

树和二叉树

文章目录 树和二叉树1.树的概念1.1特点1.2基本概念 2.二叉树2.1二叉树的定义2.2特殊的树2.3 二叉树的性质2.4二叉树的存储 二叉树的遍历 树和二叉树 1.树的概念 树是一种非线性的数据结构&#xff0c;它是由n个有限结点组成一个有具体层次关系的集合 1.1特点 没有前驱结点的…

ubuntu离线安装Ollama并部署Llama3.1 70B INT4

文章目录 1.下载Ollama2. 下载安装Ollama的安装命令文件install.sh3.安装并验证Ollama4.下载所需要的大模型文件4.1 加载.GGUF文件&#xff08;推荐、更容易&#xff09;4.2 加载.Safetensors文件&#xff08;不建议使用&#xff09; 5.配置大模型文件 参考&#xff1a; 1、 如…

15.代码随想录算法训练营第十五天|(递归)110. 平衡二叉树,257. 二叉树的所有路径*,404. 左叶子之和,222.完全二叉树的节点个数[打卡自用]

15.代码随想录算法训练营第十五天|&#xff08;递归&#xff09;110. 平衡二叉树&#xff0c;257. 二叉树的所有路径*&#xff0c;404. 左叶子之和&#xff0c;222.完全二叉树的节点个数 给定一个二叉树&#xff0c;判断它是否是 平衡二叉树 示例 1&#xff1a; 输入&#xf…

GateWay

文章目录 创建网关配置路由规则工作原理 断言过滤器默认filter全局跨域 左边的是响应式网关&#xff0c;右边是传统网关(Servlet年代) 推荐左边的 需求 创建网关 在服务模块外 新建一个gateway模块 导入依赖&#xff0c;nacos和gateway和负载均衡 配置一下 这里网关默认占80…

十一、大数据治理平台总体功能架构

大数据治理平台的功能架构图中心主题&#xff1a;数据治理 核心重点是建立健全大数据资产管理框架&#xff0c;确保数据质量、安全性、可访问性和合规性。 大数据治理平台总体功能架构图 关键功能领域 1.数据资产平台&#xff08;左侧&#xff09; 此部分主要关注数据资产本身…

网络安全 机器学习算法 计算机网络安全机制

&#xff08;一&#xff09;网络操作系统 安全 网络操作系统安全是整个网络系统安全的基础。操作系统安全机制主要包括访问控制和隔离控制。 访问控制系统一般包括主体、客体和安全访问政策 访问控制类型&#xff1a; 自主访问控制强制访问控制 访问控制措施&#xff1a; 入…

PDF扫描档智能方向识别:多模型投票机制的实践测试 救活古典书籍

2025-02-22 20:10物联全栈123 尊敬的诸位&#xff01;我是一名物联网工程师。关注我&#xff0c;持续分享最新物联网与AI资讯和开发实战。期望与您携手探寻物联网与 AI 的无尽可能 RAG知识库搭建的过程中&#xff0c;扫描档pdf的支持和准确率一直是个大家都不愿主动提起的事情…

初会学习记录

【25初级会计《实务》】第一章&#xff1a;权责发生制举例_哔哩哔哩_bilibili 务实&#xff1a; 第一章 (1)会计概念&#xff0c;职能和目标&#xff1a; 2025年2月25日&#xff1a; (2)会计假设&#xff1a; 2025年2月26日&#xff1a; (3)会计核算基础&#xff1a; 202…