Java注解
Java注解
要给一个类增强一些功能,继承、实现一个接口,还可以使用注解
可以通过使用注解增强类、方法、属性的功能
1.内置注解
如:
2.自定义注解
自定义注解如何使用?
答:结合反射使用。
注解+反射什么时候会真正使用?
答:开发框架时。
3.元注解(补充)
元数据:修饰数据的数据
元注解:修饰注解的注解,如:@Target,@Retention,@Document,@Inherited
@Target:限制注解可以使用的位置
限制注解能够使用哪些元素上(属性、方法、类);如果一个注解没有@Target描述,则该注解可以修饰任何类型的元素;如果有@Target修饰,该注解就只能用于被@Target修饰的地方。
哪些位置?ElementType枚举
public enum ElementType {
/** Class, interface (including annotation type), or enum declaration */
TYPE,//类
/** Field declaration (includes enum constants) */
FIELD,//属性
/** Method declaration */
METHOD,//方法
/** Formal parameter declaration */
PARAMETER,//形参
/** Constructor declaration */
CONSTRUCTOR,//构造函数
/** Local variable declaration */
LOCAL_VARIABLE,//局部变量
/** Annotation type declaration */
ANNOTATION_TYPE,//注释类型
/** Package declaration */
PACKAGE,//包
/**
* Type parameter declaration
*
* @since 1.8
*/
TYPE_PARAMETER,//标注类型参数
/**
* Use of a type
*
* @since 1.8
*/
TYPE_USE//用于有关类型的各种方面
}
举例代码:
//自定义注解
package com.mokuiran.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
@Retention:限制注解的生命周期
public enum RetentionPolicy {
/**
* Annotations are to be discarded by the compiler.
*/
SOURCE,//JVM直接将该注解丢弃
/**
* Annotations are to be recorded in the class file by the compiler
* but need not be retained by the VM at run time. This is the default
* behavior.
*/
CLASS,//程序在编译时,会使用注解,在运行时不会使用
/**
* Annotations are to be recorded in the class file by the compiler and
* retained by the VM at run time, so they may be read reflectively.
*
* @see java.lang.reflect.AnnotatedElement
*/
RUNTIME//程序在编译以及运行时,都会使用注解
}
举例代码:
//自定义注解
package com.mokuiran.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
//限制运用,当用这个注解时,只能用于属性,方法和类
@Document
javadoc:java帮助文档。
默认情况下,javadoc不包含注解的解释,如果现在javadoc文档中也包含对注解的说明,则需要使用@Document标注
例如,以下MyAnnotation注解,会在生成javadoc时,被显示在文档中
@Inherited:继承
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~