常见的Java注解类

发布于:2024-07-10 ⋅ 阅读:(129) ⋅ 点赞:(0)

Java 注解类大多是在 java.lang.annotation 包中定义的。这个包包括了定义注解和元注解的核心类和接口。Java 注解类主要包括几种核心注解和用于定义注解的元注解。以下是一些常见的 Java 注解类:

核心注解类

  1. @Override
    • 用于标识方法重写。编译器会检查方法是否正确地重写了超类的方法。
    • 示例:
@Override
public String toString() {
    return "This is an example";
}
@Deprecated
  • 用于标识不推荐使用的类、方法或字段。编译器会发出警告,表明该元素已过时。
  • 示例:
@Deprecated
public void oldMethod() {
    // 实现
}
@SuppressWarnings
  • 用于抑制编译器产生的特定警告。通常与编译器警告的名称一起使用。
  • 示例:
@SuppressWarnings("unchecked")
public void myMethod() {
    List rawList = new ArrayList();
    // 警告被抑制
}
@SafeVarargs
  • 用于抑制有关泛型可变参数方法的警告。只能应用于构造方法或最终方法。
  • 示例:
@SafeVarargs
public final void safeVarargsMethod(List<String>... lists) {
    // 实现
}
@FunctionalInterface
  • 用于标识函数式接口。编译器会检查该接口是否符合函数式接口的要求(即只有一个抽象方法)。
  • 示例:
@FunctionalInterface
public interface MyFunctionalInterface {
    void myMethod();
}

元注解(用于定义注解的注解)

@Retention
  • 指示注解的保留策略,确定注解在何时可见。
  • 示例:
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
    String value();
}
@Target
  • 指定注解可以应用的程序元素。
  • 示例:
@Target(ElementType.METHOD)
public @interface MyAnnotation {
    String value();
}
@Documented
  • 指示注解是否包含在 Javadoc 中。
  • 示例:
@Documented
public @interface MyAnnotation {
    String value();
}
@Inherited
  • 指示注解是否可以被子类继承。如果一个注解类型用 @Inherited 标注,那么这个注解将自动被应用到它的子类。
  • 示例:
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface MyAnnotation {
    String value();
}

使用示例

以下是一个综合示例,展示了如何使用这些注解和元注解:

import java.lang.annotation.*;
import java.lang.reflect.Method;

// 定义注解
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface MyAnnotation {
    String value();
}

// 使用注解
public class MyClass {
    @MyAnnotation(value = "Example")
    @Override
    @Deprecated
    @SuppressWarnings("unchecked")
    public void myMethod() {
        List rawList = new ArrayList();
        System.out.println("Hello, world!");
    }
}

// 读取注解
public class AnnotationTest {
    public static void main(String[] args) {
        try {
            Method method = MyClass.class.getMethod("myMethod");

            if (method.isAnnotationPresent(MyAnnotation.class)) {
                MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
                System.out.println("value: " + annotation.value());
            }

            if (method.isAnnotationPresent(Deprecated.class)) {
                System.out.println("This method is deprecated");
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }
}

通过这些注解,Java 提供了强大的元数据支持,使得代码更加清晰和可维护。元注解特别用于定义自定义注解时,控制这些注解的行为和应用范围。


网站公告

今日签到

点亮在社区的每一天
去签到