`

注解之类型 Annotations Types

    博客分类:
  • Java
 
阅读更多

1.13.1 Annotations and Annotation Types 注解和注解类型

Annotations are notes in Java programs to instruct the Java compiler to do something. Java provides three standard annotations and four standard meta-annotations.

注解是Java程序中的注释, 用于指示Java编译器去做某事. Java提供

3种标准 注解 和4种标准 元注解.

An annotation type is a special interface type.

An annotation is an instance of an annotation type.

An annotation type has a name and members.

注解类型时一种特殊的接口类型.

注解是注解类型的实例.

注解类型有名称和(方法)成员.

The information contained in an annotation takes the form of key/value pairs.

There can be zero or multiple pairs and each key has a specific type.

It can be a String, int, or other Java types.

包含在注解里的信息以 键/值 对的形式呈现.

可以有零个或多个对. 每个键拥有具体的类型.

键可以是String, int 或其他Java类型.

Annotation types with no key/value pairs are called marker annotation types.

Those with one key/value pair are referred to single-value annotation types.

There are three annotation types in Java 5: Deprecated, Override, and Suppress Warnings.

不带 key/value 对的注解类型被称为  标记(marker)注解类型.

带有一个 key/value 对的被称为 单值注解类型.

在Java 5 中有3种注解类型:  已过时, 覆盖 和  压制警告.

 

There are four other annotation types that are part of the java.lang.annotation package: Documented, Inherited, Retention, and Target.

These four annotation types are used to annotate annotations,

另有4种 元注解类型作为 java.lang.annotation包的一部分:

文档, 继承, 保留 和 目标.

1.13.2 The Annotation Interface :  Annotation接口

An annotation type is a Java interface.

All annotation types are subinterfaces of the java.lang.annotation.Annotation interface.

 

It has one method, annotation Type, that returns an java.lang.Class object.

一个注解类型是一个Java接口.

所有的注解类型都是 java.lang.annotation.Annotation 接口的子接口.

它有方法annotationType(), 返回 java.lang.Class 对象.

 

java.lang.Class<? extends Annotation> annotationType()

 In addition, any implementation of Annotation will override the equals, hashCode, and 

toString methods from the java.lang.Object class.

再者, Annotation的任何实现将会覆盖 java.lang.Object 类的 equals, hashCode 和 toString 方法.

1.13.3 Using Default Values 使用默认值

Annotation default values is used if no value is specified.

A default value is specified by adding a default clause.

 

Default value must be of a type compatible with type.

如果不指定值, 则注解的默认值被使用.

通过增加default子句指定默认值.

默认值必须类型兼容.

下面重写 @MyAnnotation 以包含默认值.

@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
  String stringValue() default "defaultString";

  int intValue() default 101;
}

 以下4种使用方式对于  @MyAnnotation 都是合法的.

@MyAnnotation()                           // both str and val default
@MyAnnotation(stringValue = "some string")        // val defaults
@MyAnnotation(intValue = 100)                  // str defaults
@MyAnnotation(stringValue = "Testing", intValue = 100) // no defaults

 

import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;

// A simple annotation type.
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
  String stringValue() default "defaultString";

  int intValue() default 101;
}

@MyAnnotation(stringValue = "for class", intValue = 100)
public class MainClass {
  // Annotate a method.
  @MyAnnotation(intValue = 100)
  public static void myMethod() {
  }

  public static void main(String[] arg) {
    try {
      MainClass ob = new MainClass();

      Method m = ob.getClass( ).getMethod("myMethod");
      Annotation[] annos = m.getAnnotations();

      System.out.println("All annotations for myMeth:");
      for(Annotation a : annos)
      System.out.println(a);

    } catch (Exception exc) {
    }
  }
}
/*
All annotations for myMeth:
@MyAnnotation(stringValue=defaultString, intValue=100)
*/

 1.13.4 Marker Annotations 标记型注解

Marker Annotations are used to mark a declaration.

A marker annotation is a special kind of annotation.

A marker annotation contains no members.

 

Using isAnnotationPresent( ) to determine if the marker is present.

标记型注解被用于标记一个声明.

标记型注解是注解中特殊的一种.

标记型注解不包含任何成员.

使用 isAnnotationPresent() 去确定 marker是否存在.

 

import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;


@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
}

@MyAnnotation
public class MainClass {
  // Annotate a method.
  @MyAnnotation()
  public static void myMethod() {
  }

  public static void main(String[] arg) {
    try {
      MainClass ob = new MainClass();

      Method m = ob.getClass( ).getMethod("myMethod");
      Annotation[] annos = m.getAnnotations();

      System.out.println("All annotations for myMeth:");
      for(Annotation a : annos)
      System.out.println(a);

    } catch (Exception exc) {
    }
  }
}
/*
All annotations for myMeth:
@MyAnnotation()
*/

 说明: 使用标记型注解时, 后面的括号 () 可有可无.

1.13.5 Single-Member Annotations 单值型注解

Single-Member Annotations contains only one member.

Single-Member Annotations allow a shorthand form of specifying the value.

 

The name of the member must be value.

单值型注解只包含一个成员.

单值型注解允许以简短形式执行值.

成员的名必须是 value

 

import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;


@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
  int value();
}

@MyAnnotation(102)
public class MainClass {
  // Annotate a method.
  @MyAnnotation(101)
  public static void myMethod() {
  }

  public static void main(String[] arg) {
    try {
      MainClass ob = new MainClass();

      Method m = ob.getClass( ).getMethod("myMethod");
      Annotation[] annos = m.getAnnotations();

      System.out.println("All annotations for myMeth:");
      for(Annotation a : annos)
      System.out.println(a);

    } catch (Exception exc) {
    }
  }
}
/*
All annotations for myMeth:
@MyAnnotation(value=101)
*/

 

 1.13.6 Creates and uses a single-member annotation 创建和使用单值型注解

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;

@Retention(RetentionPolicy.RUNTIME)
@interface MySingle {
  int value(); // this variable name must be value
}

class Single {
  @MySingle(100)
  public static void myMeth() {
    Single ob = new Single();

    try {
      Method m = ob.getClass().getMethod("myMeth");

      MySingle anno = m.getAnnotation(MySingle.class);

      System.out.println(anno.value()); // displays 100

    } catch (NoSuchMethodException exc) {
      System.out.println("Method Not Found.");
    }
  }

  public static void main(String args[]) {
    myMeth();
  }
}
//100

1.13.7 单值语法 

Using the single-value syntax when applying an annotation that has other members, if other members all have default values.

使用具有其他成员的单值型注解时(每个其他成员都有默认值), 可以使用单值语法,  

例如:

@interface SomeAnno {
  int value();
  int xyz() default 0;
}


@SomeAnno(88)

 

import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;


@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
  int value();
  int defaultValue() default 100;
}

@MyAnnotation(102)
public class MainClass {
  // Annotate a method.
  @MyAnnotation(101)
  public static void myMethod() {
  }

  public static void main(String[] arg) {
    try {
      MainClass ob = new MainClass();

      Method m = ob.getClass( ).getMethod("myMethod");
      Annotation[] annos = m.getAnnotations();

      System.out.println("All annotations for myMeth:");
      for(Annotation a : annos)
      System.out.println(a);

    } catch (Exception exc) {
    }
  }
}
/*
All annotations for myMeth:
@MyAnnotation(defaultValue=100, value=101)
*/

 

 

 1.13.8 一些限制 some restrictions

No annotation can inherit another.

All methods declared by an annotation must be without parameters.

Annotations cannot be generic.

They cannot specify a throws clause.

They must return one of the following:

一个注解不可以继承另一个注解.

注解中声明的所有方法, 必须是没有参数的.

注解不可以是泛型的.

注解不可以指定throws子句.

注解必须返回如下之一:

A simple type, such as int or double,

          An object of type String or Class

          An enum type

          Another annotation type

          An array of one of the preceding types

一个简答类型, 比如 int 或 double,

类型String或Class的一个对象,

一个 枚举(enum) 类型,

另一个 注解类型

以上某类型的数组.

1.13.9 例子: 一个标记型注解

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;

@Retention(RetentionPolicy.RUNTIME)
@interface MyMarker {
}

class Marker {
  @MyMarker
  public static void myMeth() {
    Marker ob = new Marker();

    try {
      Method m = ob.getClass().getMethod("myMeth");

      if (m.isAnnotationPresent(MyMarker.class))
        System.out.println("MyMarker is present.");

    } catch (NoSuchMethodException exc) {
      System.out.println("Method Not Found.");
    }
  }

  public static void main(String args[]) {
    myMeth();
  }
}
//MyMarker is present.

 

 

分享到:
评论

相关推荐

    error_prone_annotations-2.0.18-API文档-中文版.zip

    赠送jar包:error_prone_annotations-2.0.18.jar; 赠送原API文档:error_prone_annotations-2.0.18-javadoc.jar; ...人性化翻译,文档中的代码和结构保持不变,注释和说明精准翻译,请放心使用。

    Python库 | types_beautifulsoup4-4.9.2-py3-none-any.whl

    "types_"前缀表明这个库还包含了类型注解(Type Annotations),这是Python 3.5引入的新特性,用于提高代码的可读性和静态分析工具的准确性。类型注解可以让开发者在不运行代码的情况下了解函数、方法和变量的数据...

    PyPI 官网下载 | types_first-0.1.1-py2.py3-none-any.whl

    在Python世界中,类型注解(Type Annotations)自Python 3.5引入,允许程序员在代码中添加类型信息,提高代码的可读性、可维护性和静态分析能力。`types_first`库可能专注于这个领域,帮助开发者更好地利用类型注解...

    Python库 | types_attrs-0.1.1-py2.py3-none-any.whl

    在Python中,类型注解(type annotations)是自Python 3.5引入的一个功能,用于提供静态类型检查,帮助开发者在代码执行前发现潜在的类型错误。`types_attrs`库进一步扩展了这一功能,它提供了更强大的类型检查和...

    一组基本的TypeScript类型

    14. **类型注解(Type Annotations)** 类型注解是TypeScript中用于指定变量、函数参数和返回值类型的语法,如`function greet(name: string): string`。这提供了编译时类型检查。 15. **类型推断(Type Inference...

    android -仿thinkandroid 注解标签的实现

    此外,ThinkAndroid的注解实现可能还涉及使用元注解(meta-annotations),即注解的注解。元注解可以为自定义注解添加额外的行为或属性,比如`@Retention`和`@Target`,它们分别指定注解的生命周期和可应用的位置。 ...

    Python库 | types-aiobotocore-s3control-2.1.1.tar.gz

    4. **类型注解(Type Annotations)**:在Python中,类型注解是一种声明变量、函数参数和返回值类型的非强制性方式。`types-`前缀通常表示这个库是为其他库提供类型提示(Type Hints)的,这有助于静态类型检查工具...

    TypeScript 入门教程.pdf

    这种类型检查通过类型注解(type annotations)实现,如 `let x: number` 定义了一个数字类型的变量 x。TypeScript 的类型系统还包括联合类型(union types)、交叉类型(intersection types)以及类型推断(type ...

    eclipse注释模板以及使用方法

    - 在右侧的“Annotation Types”列表中,你可以看到预设的注释类型,如Java Doc、Line Comment等。点击“New...”按钮创建一个新的注释类型。 - 输入新注释类型的名称,例如“自定义Java注释”,并选择一个独特的...

    core_types

    12. **类型注解(Type Annotations)**: 类型注解用于指定变量、函数参数和函数返回值的类型,有助于编译器进行类型检查。 以上就是`core_types`中涉及的TypeScript核心类型及其用法,理解和掌握这些类型对于编写...

    retype:将.pyi存根中的类型注释重新应用于代码库

    重新输入 将.pyi存根中的类型注释重新应用于代码库。用法Usage: retype [OPTIONS] [SRC]... Re-apply type annotations from .pyi stubs to your codebase.Options: -p, --pyi-dir DIRECTORY Where to find .pyi ...

    Retrofit自定义请求参数注解的实现思路

    ServiceMethod 对象的构造函数中,我们需要关注三个属性:methodAnnotations、parameterTypes 和 parameterAnnotationsArray。 自定义请求参数注解的实现 为了实现自定义请求参数注解,我们需要继承 ...

    Haskell教程(中文版)

    此外,利用内联(inlining)和严格性注解(strictness annotations)也能改善性能。 ### 15. 类型级编程 Haskell支持类型级编程,允许在类型层面上进行计算,进一步增强了类型系统的表达能力。 本教程“Yet ...

    你不知道的 TypeScript 高级类型(小结)

    类型注解(Type Annotations) TypeScript 中的类型注解是声明变量、函数参数或返回值类型的关键。例如: ```typescript function greet(name: string): string { return `Hello, ${name}!`; } ``` 映射类型...

    java specification

    12. 枚举和注解(Enums and Annotations):解释了枚举类型如何在Java中定义和使用,以及如何创建和使用注解。 13. 预定义类和接口(Predefined Classes and Interfaces):对Java标准库中的关键类和接口(如System...

    The Java Programming Language.4th.Edition.Aug.2005.pdf

    - **注解(Annotations)**:注解是J2SE 5.0引入的另一个重要特性,它可以在编译或运行时提供元数据,被广泛用于框架开发中,例如Spring框架中的依赖注入。 ##### 2. 类和方法的增强 - **自动装箱(Auto-boxing)*...

    awesome-python-typing:很棒的Python类型,存根,插件和与之配合使用的工具的集合

    Python是一种动态类型的编程语言,但在Python 3.5及以上版本中引入了类型注解(Type Annotations),这使得在保持灵活性的同时,可以增加代码的可读性和可维护性。`awesome-python-typing`是一个资源丰富的集合,...

    kotlin in chinese

    Kotlin支持注解(annotations),注解可以用来提供元数据,不会直接影响代码的行为,但可以被编译器或运行时环境使用。Kotlin的反射(reflection)API允许在运行时访问关于类的详细信息,这对于创建通用的库和框架...

    PyPI 官网下载 | mypy-boto3-ebs-1.11.3.0.tar.gz

    类型注解不仅可以帮助开发者在编写代码时避免类型错误,还可以让IDE(如VSCode、PyCharm等)提供更准确的智能提示,提高开发效率。此外,当团队合作或者项目规模较大时,类型检查也成为了保证代码一致性的重要手段。...

Global site tag (gtag.js) - Google Analytics