常用注解
- @Override,表示当前的方法定义将覆盖超类中的方法。
- @Deprecated,编译器在编译阶段遇到这个注解时会发出提醒警告,告诉开发者正在调用一个过时的元素比如过时的方法、过时的类、过时的成员变量。
- @SuppressWarnings,阻止警告的意思。之前说过调用被 @Deprecated 注解的方法后,编译器会警告提醒,而有时候开发者会忽略这种警告,他们可以在调用的地方通过 @SuppressWarnings 达到目的。
元注解
@Target
- ElementType.ANNOTATION_TYPE, 可以给一个注解进行注解
- ElementType.CONSTRUCTOR, 可以给构造方法进行注解
- ElementType.FIELD, 可以给属性进行注解
- ElementType.LOCAL_VARIABLE, 可以给局部变量进行注解
- ElementType.METHOD, 可以给方法进行注解
- ElementType.PACKAGE, 可以给一个包进行注解
- ElementType.PARAMETER, 可以给一个方法内的参数进行注解
- ElementType.TYPE, 可以给一个类型进行注解,比如类、接口、枚举
@Retention
表示需要在什么级别保存该注解信息。可选的RetentionPolicy参数包括:
SOURCE:注解将被编译器丢弃
CLASS:注解在class文件中可用,但会被VM丢弃
RUNTIME:VM将在运行期间保留注解,因此可以通过反射机制读取注解的信息。如果一个注解要在运行时被成功提取,那么 @Retention(RetentionPolicy.RUNTIME) 是必须的。
@Document
将注解包含在Javadoc中
@Inherited
允许子类继承父类中的注解
自定义注解
定义(使用 @interface )
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface PersonName {
public String name();
}
注解在只有一个元素且该元素的名称是value的情况下,在使用注解的时候可以省略“value=”,直接写需要的值即可
使用
在属性或者方法声明前使用@,需要传入参数
public class Student {
@PersonName(name="jxl")
public String name1;
@PersonName(name="xlj")
public String name2;
public void say(String name){
System.out.println("My name is "+name);
}
}
获取注解(反射机制)
判断对象是否用了某个注解
public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) {}
通过 getAnnotation() 或 getAnnotations() 来获取 Annotation对象
public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {}
public Annotation[] getAnnotations() {}
在类上的注解调用:
@TestAnnotation()
public class Test {
public static void main(String[] args) {
boolean hasAnnotation = Test.class.isAnnotationPresent(TestAnnotation.class);
if ( hasAnnotation ) {
TestAnnotation testAnnotation = Test.class.getAnnotation(TestAnnotation.class);
System.out.println("id:"+testAnnotation.id());
System.out.println("msg:"+testAnnotation.msg());
}
}
}
在属性上的注解调用:
Student stu = new Student();
Field[] fields = Student.class.getDeclaredFields();
for(Field field:fields){
PersonName pn = field.getAnnotation(PersonName.class);
stu.say(pn.name());
}
在方法上的注解调用(假设注解@Perform为方法testMethod()上的注解):
Method testMethod = Test.class.getDeclaredMethod("testMethod");
Annotation[] ans = testMethod.getAnnotations();
for( int i = 0;i < ans.length;i++) {
System.out.println("method testMethod annotation:"+ans[i]
.annotationType().getSimpleName());
}
注解的使用场景
当开发者使用了Annotation 修饰了类、方法、Field 等成员之后,这些 Annotation 不会自己生效,必须由开发者提供相应的代码来提取并处理 Annotation 信息。这些处理提取和处理 Annotation 的代码统称为 APT(Annotation Processing Tool)。
参考博客
https://www.cnblogs.com/be-forward-to-help-others/p/6846821.html
本文深入解析Java注解的使用,包括@Override、@Deprecated、@SuppressWarnings等常用注解,以及@Target、@Retention、@Document等元注解的功能与应用场景。同时,文章详细介绍了自定义注解的定义、使用及通过反射机制获取注解信息的方法。
662

被折叠的 条评论
为什么被折叠?



