Java注解 Annotation

摘要:
refAnnotations,aformofmetadata,providesdataaboutaprogramthatisnotpartoftheprogramitself.Annotationshavenodirecteffectontheoperationofthecodetheyannotate.Annotationshaveanumberofuses,amongthem:Informat

ref

Annotations, a form of metadata, provides data about a program that is not
part of the program itself. Annotations have no direct effect on the operation
of the code they annotate.

Annotations have a number of uses, among them:

  • Information for the compiler
  • Compile-time and deployment-time processing
  • Runtime processing

Format and Effect

@annotationName{field = val}

Declarations: declarations of classes, fields, methods, and other elements. When used on
declaration often appears, by convention on its own lines.

  • Class instance creation expression

new @Interned MyObject();

  • Type cast

myString = (@NonNull String) str;

  • implements clause

class UnmodifiableList<T> implements @Readonly List<@Readonly T> {...}

  • Thrown exception declaration
void monitorTemperature() throws 
@Critical TemperatureException{...}

Declaring an Annotation Type

Define the annotation type:

@interface ClassPreamble{
	String author();
	String date();
	int currentVersion() default 1;
	String lastModified(0 default "N/A";
	String lastModifiedBy() default "N/A";
	// Note use of array
    String [] reviewers();

Usage:

  @ClassPreamble (
  author = "Sonnet"
  date = "2021-06-09",
  currentVersion = 6,
  lastModified = "2021-06-10",
  reviewers = {"Alice", "Bob", "Caws"}
  )
  public class Generation3List extends Gereration2List{
	//code here
  }

Note: To make the information in @ClassPreamble appear in
Javadoc-generated documentation, you must annotate the @ClassPreamble definition with the @Documented annotation:

// import this to use @Documented
import java.lang.annotation.*;

@Documented
@interface ClassPreamble {

   // Annotation element definitions
}

Predefined Annotation Types

Defined in java.lang

  • @Deprecated Mark the element as deprecated and should no longer be used.

For method be marked as deprecated, it should also be documentated using Javadoc
@deprecated tag.

  // Javadoc comment follows
    /**
     * @deprecated
     * explanation of why it was deprecated
     */
    @Deprecated
    static void deprecatedMethod() { }
}

**Note: @deprecated in Javadoc while @Deprecated in annotation **

  • Override informs the compiler that the element is meant to overide an element
    declared in a superclass.

  • @SuppressWarnings annotation tells the compiler to suppress specific warnings that it would otherwise generate.(suppress 阻止,抑制)

   // use a deprecated method and tell 
   // compiler not to generate a warning
   @SuppressWarnings("deprecation")
    void useDeprecatedMethod() {
        // deprecation warning
        // - suppressed
        objectOne.deprecatedMethod();
    }
@SuppressWarnings({"unchecked", "deprecation"})
  • @SafeVarargs @SafeVarargs annotation, when applied to a method or constructor,
    asserts that the code does not perform potentially unsafe operations on its varargs parameter.
    When this annotation type is used, unchecked warnings relating to varargs usage are suppressed.

  • @FunctionalInterface @FunctionalInterface annotation, introduced in Java SE 8,
    indicates that the type declaration is intended to be a functional interface, as defined by the Java Language Specification.

Annotations That Apply to Other Annotations

Annotations that apply to other annotations are called meta-annotations. There are several meta-annotation types defined in java.lang.annotation.

  • @Retention @Retention annotation specifies how the marked annotation is stored:

  • RetentionPolicy.SOURCE – The marked annotation is retained only in the source level and is ignored by the compiler.

  • RetentionPolicy.CLASS – The marked annotation is retained by the compiler at compile time, but is ignored by the Java Virtual Machine (JVM).

  • RetentionPolicy.RUNTIME – The marked annotation is retained by the JVM so it can be used by the runtime environment.

  • @Documented @Documented annotation indicates that whenever the specified annotation
    is used those elements should be documented using the Javadoc tool.
    (By default, annotations are not included in Javadoc.) For more information, see the Javadoc tools page.

  • @Target @Target annotation marks another annotation to restrict what kind
    of Java elements the annotation can be applied to.
    A target annotation specifies one of the following element types as its value:

  • ElementType.ANNOTATION_TYPE can be applied to an annotation type.

  • ElementType.CONSTRUCTOR can be applied to a constructor.

  • ElementType.FIELD can be applied to a field or property.

  • ElementType.LOCAL_VARIABLE can be applied to a local variable.

  • ElementType.METHOD can be applied to a method-level annotation.

  • ElementType.PACKAGE can be applied to a package declaration.

  • ElementType.PARAMETER can be applied to the parameters of a method.

  • ElementType.TYPE can be applied to any element of a class.

  • @Inherited @Inherited annotation indicates that the annotation type can be
    inherited from the super class. (This is not true by default.) When the user
    queries the annotation type and the class has no annotation for this type,
    the class' superclass is queried for the annotation type. This annotation applies only to class declarations.

  • @Repeatable @Repeatable annotation, introduced in Java SE 8, indicates
    that the marked annotation can be applied more than once to the same declaration
    or type use. For more information, see Repeating Annotations.

Repeatable Annotations

There are some situations where you want to apply the same annotation to a
declaration or type use. As of the Java SE 8 release, repeating annotations enable you to do this.

  1. Declare a Repeatable Annotation Type
import java.lang.annotation.Repeatable;

@Repeatable(Schedules.class)
public @interface Schedule {
  String dayOfMonth() default "first";
  String dayOfWeek() default "Mon";
  int hour() default 12;
}
  1. Declare the Containing Annotation Type
public @interface Schedules {
    Schedule[] value();
}

免责声明:文章转载自《Java注解 Annotation》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇EhCache缓存的使用C#窗体如何通过keybd_event()函数模拟键盘按键(组合键)产生事件下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

随便看看

移动端媒体查询的一些尺寸参考

device-width是设备实际的宽度,不会随着屏幕的旋转而改变,因此并不适合开发响应式网站。比如iphone5s的屏幕分辨率宽为640,由于retina显示策略,当scale设置为1的时候,对应的media中取到的width为320,当scale设置为0.5的时候,width为640,而device-width始终是320。总结1.device-widt...

backgroundsize

当背景大小值为和时,可以设置两个值,也可以设置一个值。当只取一个值时,第二个值相当于auto,但此处的auto不会将背景图像的高度保持在其原始高度,而是与第一个值相同。此外,如果只取一个值,宽度和高度将相同,这相当于背景大小:80%自动。...

硬中断与软中断的区别!

在多核系统上,一个中断通常只能中断一个CPU(也有一种特殊情况,即主机上有一个硬件通道。它可以在没有主CPU支持的情况下同时处理多个中断。软中断:1。软中断与硬中断非常相似。生成软中断的进程必须是当前正在运行的进程,因此它们不会中断CPU。...

WPF绑定功能常用属性介绍

这是实质上是System.Windows.Data.BindingMode.OneWay绑定的一种简化形式,它在源值不更改的情况下提供更好的性能。确定依赖属性绑定在默认情况下是单向还是双向的编程方法是:使用System.Windows.DependencyProperty.GetMetadata获取属性的属性元数据,然后检查System.Windows.Fr...

linux下ifconfig, DNS以及route配置

Linux基本网络配置命令1.ifconfig查看网络接口信息。普通用户使用的ifconfig的完整路径:/sbin/ifconfigifconfig网络接口名称:显示指定接口的详细信息。...

每个文件之间延迟启动批处理bat方法之一

延迟在文件之间启动批处理的方法之一:。文本→. bat将扩展名更改为.bat或在txt中将其另存为.bat。例如,如果B是包含空格的路径名,请使用引号“”,否则将找不到文件。批处理bat要运行的文件位于同一目录文件夹@echoffstart xiongmaoshu.jpgping127.0.0.1-n 10&gt;批处理bat和文件是否位于同一目录文...