java编程思想--注解

注解(Annotations)

注解(也被称为元数据)为我们在代码中添加信息提供了一种形式化的方法,是我们可以在稍后某个时刻非常方便地使用这些数据.

  1. 它可以提供用来完整的描述程序所需的信息,而这些信息是无法用Java来表达的.因此,注解使得我们能够以将由编译器来测试和验证的格式,存储有关程序的额外信息.
  2. 注解可以用来生成描述符文件,甚至或是新的类定义,并且有助于减轻编写”样板”代码的负担.
  3. 同时,注解的优点还包括:更加干净易读的代码以及编译器类型检查等.
  4. 虽然JavaSE5预先定义了一些元数据,但是主要还是需要程序员自己添加新的注解,并且按自己的方式使用它们.

    • @Override, to indicate that a method definition is intended to override a method in the base class. This generates a compiler error if you accidentally misspell the method name or give an improper signature.2
    • @Deprecated, to produce a compiler warning if this element is used.
    • @SuppressWarnings, to turn off inappropriate compiler warnings. This annotation is allowed but not supported in earlier releases of Java SE5 (it was ignored).
  5. 注解是真正的语言级的概念,一旦构造出来,就像有编译期的类型检查保护.

20.1基本语法

  1. 定义注解:与其他任何接口一样,注解也将会编译成class文件.
//: net/mindview/atunit/Test.java
// The @Test tag.
package net.mindview.atunit;
import java.lang.annotation.*;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Test {} ///:~
  1. @Test的定义很像一个空的接口.定义注解时,会需要一些元注解(meta-annotation).
  2. @Target用来定义你的注解将应用于什么地方(例如是一个方法或者一个域)
  3. @Rectetion用来定义该注解在哪一个级别可用,在源代码中(SOURCE) 类文件中(CLASS) 或者运行时(RUNTIME)
  4. 注解的元素看起来就像接口的方法,唯一的区别是你可以为其指定默认值.
  5. 没有元素的注解称为标记注解(marker annotation)
  6. 默认值限制:

The compiler is quite picky about default element values. No element can have an unspecified value. This means that elements must either have default values or values provided by the class that uses the annotation.
There is another restriction, which is that none of the non-primitive type elements are allowed to take null as a value, either when declared in the source code or when defined as a default value in the annotation interface. This makes it hard to write a processor that acts on the presence or absence of an element, because every element is effectively present in every annotation declaration. You can get around this by checking for specific values, like empty strings or negative values:

  1. 生成外部文件

20.3使用apt注解

  1. 注解处理工具apt,这是Sun为了帮助注解的处理过程而提供的工具.
  2. 与javac一样,apt被设计为操作Java源文件,而不是编译后的类.

20.5单元测试自己网上搜索吧!!!书上真的是看不懂

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值