前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java官方笔记10注解

Java官方笔记10注解

作者头像
dongfanger
发布2023-07-10 16:37:08
1550
发布2023-07-10 16:37:08
举报
文章被收录于专栏:dongfangerdongfanger

注解

注解的作用:

  • Information for the compiler — Annotations can be used by the compiler to detect errors or suppress warnings.
  • Compile-time and deployment-time processing — Software tools can process annotation information to generate code, XML files, and so forth.
  • Runtime processing — Some annotations are available to be examined at runtime.

注解格式,使用@

代码语言:javascript
复制
@Entity

带key-value:

代码语言:javascript
复制
@Author(
   name = "Benjamin Franklin",
   date = "3/27/2003"
)
class MyClass { ... }

只有1个key时可以省略key:

代码语言:javascript
复制
@SuppressWarnings(value = "unchecked")
void myMethod() { ... }
代码语言:javascript
复制
@SuppressWarnings("unchecked")
void myMethod() { ... }

同时使用多个注解:

代码语言:javascript
复制
@Author(name = "Jane Doe")
@EBook
class MyClass { ... }

The annotation type can be one of the types that are defined in the java.lang or java.lang.annotation packages of the Java SE API.

哪里能用注解

① Annotations can be applied to declarations: declarations of classes, fields, methods, and other program elements.

② Java SE 8,annotations can also be applied to the use of types

Class instance creation expression:

代码语言:javascript
复制
new @Interned MyObject();

Type cast:

代码语言:javascript
复制
myString = (@NonNull String) str;

implements clause:

代码语言:javascript
复制
class UnmodifiableList<T> implements
  @Readonly List<@Readonly T> { ... }

Thrown exception declaration:

代码语言:javascript
复制
void monitorTemperature() throws
  @Critical TemperatureException { ... }

自定义注解

使用@interface

代码语言:javascript
复制
@interface ClassPreamble {
   String author();
   String date();
   int currentRevision() default 1;
   String lastModified() default "N/A";
   String lastModifiedBy() default "N/A";
   // Note use of array
   String[] reviewers();
}

注解其实也是一种接口,只是要使用@来声明。

使用:

代码语言:javascript
复制
@ClassPreamble (
   author = "John Doe",
   date = "3/17/2002",
   currentRevision = 6,
   lastModified = "4/12/2004",
   lastModifiedBy = "Jane Doe",
   // Note array notation
   reviewers = {"Alice", "Bob", "Cindy"}
)
public class Generation3List extends Generation2List {

// class code goes here

}

Java预置注解

@Deprecated

代码语言:javascript
复制
// Javadoc comment follows
/**
 * @deprecated
 * explanation of why it was deprecated
 */
@Deprecated
static void deprecatedMethod() { }

@Override

代码语言:javascript
复制
// mark method as a superclass method
// that has been overridden
@Override 
int overriddenMethod() { }

@SuppressWarnings

代码语言:javascript
复制
// use a deprecated method and tell 
// compiler not to generate a warning
@SuppressWarnings("deprecation")
void useDeprecatedMethod() {
    // deprecation warning
    // - suppressed
    objectOne.deprecatedMethod();
}

@SafeVarargs

@FunctionalInterface

注解上的注解:Annotations that apply to other annotations are called meta-annotations. There are several meta-annotation types defined in java.lang.annotation.

@Retention

  • 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

@Target

  • 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.MODULE can be applied to a module declaration.
  • ElementType.PACKAGE can be applied to a package declaration.
  • ElementType.PARAMETER can be applied to the parameters of a method.
  • ElementType.RECORD_COMPONENT can be applied to the component of a record.
  • ElementType.TYPE can be applied to the declaration of a class, an abtract class, an interface, an annotation interface, an enumeration, or a record declaration.
  • ElementType.TYPE_PARAMETER can be applied on the parameters of a type.
  • ElementType.TYPE_USE can be applied where a type is used, for instance on the declaration of a field.

@Inherited

@Repeatable

重复注解也是允许的:

代码语言:javascript
复制
@Schedule(dayOfMonth="last")
@Schedule(dayOfWeek="Fri", hour="23")
public void doPeriodicCleanup() { ... }

重复注解的定义要用到@Repeatable:

代码语言:javascript
复制
@Repeatable(Schedules.class)
public @interface Schedule {
  String dayOfMonth() default "first";
  String dayOfWeek() default "Mon";
  int hour() default 12;
}

并且,The containing annotation type must have a value element with an array type:

代码语言:javascript
复制
public @interface Schedules {
    Schedule[] value();
}

the containing annotation type is @Schedules, so repeating @Schedule annotations is stored in an @Schedules annotation.

Schedule[] value()是一个没有参数、返回类型为Schedule[]的方法的声明,它是一个抽象方法。事实上,这个方法声明是用来定义注解的属性的,与普通方法不同的是,它没有方法体,只有方法声明,而方法的具体实现则由使用该注解的代码来完成。在使用该注解时,也可以通过指定该属性的值来进行赋值操作,例如:

代码语言:javascript
复制
@Schedules({
        @Schedule(dayOfMonth="last"),
        @Schedule(dayOfWeek="Fri", hour="23")
})
public class MyScheduledTask {
    // ...
}

在上述代码中,我们使用了@Schedules注解,并且指定了它的value属性,也就是给Schedule[] value()方法赋上相应的值。注意到,该属性的值是一个注解数组,因此需要使用大括号{}将多个注解组合起来。

参考资料: Annotations https://dev.java/learn/annotations/

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2023-06-17,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 注解
  • 哪里能用注解
  • 自定义注解
  • Java预置注解
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档