java annoation 注解 详解

注释有3中基本类型

a.标记注释 --没有变量,只有名称标识。例如 @annotation
b.单一值注释 --在标记注释的基础上提供一段数据。如 @annotation(“data”)
c.完整注释 --可以包括多个数据成员,每个数据成员由名称和值构成。
@annotation(val1="data1",val2="data2")

2.Java的“注释”

Java中提供3个内置注释类型

a. Override ,只能用于方法(不能用于类,包声明或者其他构造)
作用:可以保证编译时候Override函数的声明正确性
用法:@Override
public void fun(){..}

b.Deprecated 同样只能作用与方法
作用:对不应再使用的方法进行注解
用法:@Deprecated public void fun{...} //它们说这个注释跟函数要同一行

c.SupressWarnings 可以注释一段代码
作用:关闭特定的警告信息,例如你在使用泛型的时候未指定类型
用法: @SupressWarnings(value={"unchecked"})
..代码

Java中还提供了四种元注释,专门负责注释其他的注释

@Target 表示该注释可以用于什么地方。可用的ElementType参数包括:
CONSTRUCTOR : 构造器的声明
FIELD : 域声明(包括enum实例)
LOCAL_VARIABLE : 局部变量声明
METHOD : 方法声明
PACKAGE : 包声明
PARAMETER : 参数声明
TYPE : 类、接口 (包括注解类型) 或enum声明

@Retention 表示需要在什么级别保存该注释信息。可选的RetentionPoicy参数包括:
SOURCE : 注释将被编译器丢掉
CLASS : 注释在class文件中可用,但会被VM丢弃
RUNTIME : VM将在运行时也保留注释,因此可以通过反射机制读取注释的信息。

@Documented 将注释包含在JavaDoc中

@Inheried 允许子类继承父类中的注释。
3. 在Java中定义自己的注释

Java语言支持一种新的类型--注释类型(annotation type),跟普通类差不多,在类中以符号( @ )的形式注释其他 Java 代码

下面将通过一个简单的例子来实现(代码是Brett McLaughlin 的)

@interface 申明

i.简单的注释类型
package com.oreilly.tiger.ch06;
/**
* Marker annotation to indicate that a method or class
* is still in progress.
*/
public @interface InProgress { }

ii.使用定制的注释类型
@com.oreilly.tiger.ch06.InProgress
public void calculateInterest(float amout,float rate)
{
//Need to finish this method later
}

iii.添加成员
package com.oreilly.tiger.ch06;
/**
* Marker annotation to indicate that a method or class
* is still in progress.
*/
public @interface InProgress {
String value();
}

@com.oreilly.tiger.ch06.InProgress
@TODO("Figure out the amount of interest per month")
//或者@TODO(value="Figure out the amount of interest per month")
public void calculateInterest(float amount,float rate)
{
}

iv.设置默认值
package com.oreilly.tiger.ch06;
public @interface GroupTODO {
public enum Serverity { CRITICAL,IMPORTANT,IRIVIAL,DOCMENTATION };
Severity severity()
default Severity.IMPORTANT;
String item ();
String assignedTo();
String dateAssigned();
}
}

v.使用默认值
@com.oreilly.tiger.ch06.InProgress
@GroupTODO(
item="Figure out the amount of interest per month",
assignedTo = "Brett McLaughlin",
dateAssigned = "08/04/2004"
)

public void calculateInterest(float amount, float rate)
{
//Need to finish this method later
}

vi.改写默认值
@com.oreilly.tiger.ch06.InProgress
@GroupTODO
{
severity = GroupTODO.Severity.DOCUMENTATION,
item = "Need to explain how this rather unusal method works",
assignedTo = "Jon Stevens",
dateAssigned = "07/30/2004"
}
转至:http://javaopen.iteye.com/blog/645915
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值