注解
内置的注解
Java 定义了一套注解,共有 7 个,3 个在 java.lang 中,剩下 4 个在 java.lang.annotation 中。
作用在代码的注解是
@Override - 检查该方法是否是重写方法。如果发现其父类,或者是引用的接口中并没有该方法时,会报编译错误。
@Deprecated - 标记过时方法。如果使用该方法,会报编译警告。
@SuppressWarnings - 指示编译器去忽略注解中声明的警告。
作用在其他注解的注解(或者说 元注解)是:
@Retention - 标识这个注解怎么保存,是只在代码中,还是编入class文件中,或者是在运行时可以通过反射访问。
@Documented - 标记这些注解是否包含在用户文档中。
@Target - 标记这个注解应该是哪种 Java 成员。
@Inherited - 标记这个注解是继承于哪个注解类(默认 注解并没有继承于任何子类)
从 Java 7 开始,额外添加了 3 个注解:
@SafeVarargs - Java 7 开始支持,忽略任何使用参数为泛型变量的方法或构造函数调用产生的警告。
@FunctionalInterface - Java 8 开始支持,标识一个匿名函数或函数式接口。
@Repeatable - Java 8 开始支持,标识某注解可以在同一个声明上使用多次。
@Rentention
- RententionPolicy.SOURCE:Annotation信息仅存在于编译器处理期间,编译器处理完之后就没有该Annotation信息了
- CLASS:编译器将Annotation存储于类对应的.class文件中。默认行为
- RUNTIME:编译器将Annotation存储于class文件中,并且可由JVM读入,常用
@Target
指明注解可以放在什么地方,若定义注解时没有Target任何位置都可以用这个注解:
- ElementType.TYPE:类、接口(包括注释类型)或枚举声明
- ElementType.FIELD:字段声明(包括枚举常量)
- ElementType.METHOD:方法声明
- ElementType.PARAMETER:参数声明
反射使用注解
import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @Classname: MyAnnotation * @Description: 定义一个注释 * @Author: Stonffe * @Date: 2022/11/30 16:46 */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface MyAnnotation { String value() default "hello"; } /** * @Classname: Person * @Description: * @Author: Stonffe * @Date: 2022/11/30 16:51 */ public class Person { @MyAnnotation public void nothing(){ System.out.println("nothing"); } @MyAnnotation(value = "i wirte something here") public void something(String name,int age){ System.out.println("the age of"+name+"is"+name); } } import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class Main { public static void main(String[] args) throws IOException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { Person person = new Person(); Class<? extends Person> personClass = person.getClass(); Method nothing = personClass.getMethod("nothing", new Class[]{}); nothing.invoke(person,new Object[]{}); MyAnnotation annotation = nothing.getAnnotation(MyAnnotation.class); String value1 = annotation.value(); System.out.println(value1); Method something = personClass.getMethod("something", String.class, int.class); something.invoke(person,"yukito",18); MyAnnotation annotation1 = something.getAnnotation(MyAnnotation.class); String value2 = annotation1.value(); System.out.println(value2); } }
本文作者:xiaoovo
本文链接:https://www.cnblogs.com/xiaoovo/p/16939136.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步