关键字:   Annotation,Java    

在创建EJB组件时,必需提供一些定义,使得EJB组件使用一些服务例如:安全服务,持久化服务,事务服务。EJB容器可以提供这些服务,这样EJB只要实现业务逻辑就可以了。但是说到底EJB容器使用EJB组件的元数据来提供这些服务,在以前EJB的元数据是以XML配置文件形式出现的,这些配置文件与EJB源文件是分开的。
EJB的部署人员无法了解EJB本身的信息,如果EJB组件的创建者用注释(Annotation)的方法将这些配置服务的信息和代码放在一起,这样EJB的部署者就可以了解EJB的信息,EJB的home接口可以使用Annotation自动生成,当然到目前为止更好的是在简单的Java Object上使用Annotations。

一 什么是Annotation

在已经发布的JDK1.5(tiger)中增加新的特色叫 Annotation。Annotation提供一种机制,将程序的元素如:类,方法,属性,参数,本地变量,包和元数据联系起来。这样编译器可以将元数据存储在Class文件中。这样虚拟机和其它对象可以根据这些元数据来决定如何使用这些程序元素或改变它们的行为。

二 定义一个简单的Annotation并使用它

1.定义Annotation

定义一个Annotation是什么简单的,它采取的是类似于Interface的定义方式: “@+annotation类型名称+(..逗号分割的name-value对...)”

代码
  1. //Example 1
  2. package sz.starbex.bill.annotation;
  3. import java.lang.annotation.Retention;
  4. import java.lang.annotation.RetentionPolicy;
  5. import java.lang.annotation.Target;
  6. import java.lang.annotation.ElementType;
  7. @Retention(RetentionPolicy.RUNTIME)
  8. @Target(ElementType.METHOD)
  9. public @interface SimpleAnnotation {
  10. String value();
  11. }

<script type="text/javascript">render_code();</script>

@Retention这个meta-annotation表示我们创建的SimpleAnnotation这个Annotation将会存储在Class文件中,并在java

VM运行时加载它。@Target这个meta-annotation表示我们创建的SimplwAnnotation将会为描述方法,而@interface SimpleAnnotation是我们自定义的Annotation,它有一个成员叫value,返回值是String。

2.使用Annotation

代码
  1. //Example 2
  2. package sz.starbex.bill.annotation;
  3. import sz.starbex.bill.annotation.SimpleAnnotation;
  4. public class UsingSimpleAnnotation {
  5. @SimpleAnnotation(value="Pass:This method will Pass")//注意name=value的用法
  6. public void pass(){
  7. if(10>5) System.out.println("测试通过");
  8. }
  9. @SimpleAnnotation("Fail:This method will Fail")//注意name=value的用法
  10. public void fail(){
  11. if(10<5) System.out.println("测试失败");
  12. }
  13. }

<script type="text/javascript">render_code();</script>

一个Annotation用于程序元素(在本例中是method),在method方法之前用(@Annotation名称(name=value,name=value.....)。在本例中是@SimpleAnnotation(value="Pass:This method will Pass")。每个annotation具有一个名字和成员个数>=0,当只有一个单一的成员时,这个成员就是value。我们也可以这样写 @SimpleAnnotation("Fail:This method will Fail")。至此@SimpleAnnotation将Pass和Fail联系起来了。

3.在运行时访问Annotation

一旦Annotation与程序元素联系起来,我们可以通过反射访问它们并可以取得它们的值。我们使用一个新的interface:java.lang.reflect.AnnotatedElement。java.lang.reflect.AnnotatedElement接口中的方法有:

a. boolean isAnnotationPresent(Class annotationType)

如果指定类型的注释存在于此元素上,则返回 true,否则返回 false。
b. T getAnnotation(Class annotationType)

如果存在该元素的指定类型的注释,则返回这些注释,否则返回 null。
c. Annotation[] getAnnotations()

返回此元素上存在的所有注释。
d. Annotation[] getDeclaredAnnotations()

返回直接存在于此元素上的所有注释。
你要注意 isAnnotationPresent和getAnnotation方法,它们使用了Generics,请参考我的Java 范型的Blog。

下面我们列出一些实现了AnnotatedElement 接口的类

1. java.lang.reflect.AccessibleObject

2. java.lang.Class

3. java.lang.reflect.Constructor

4. java.lang.reflect.Field

5. java.lang.reflect.Method

6. java.lang.Package

下面的Example程序说明了如何在运行环境访问Annotation

代码
  1. package sz.starbex.bill.annotation;
  2. import sz.starbex.bill.annotation.SimpleAnnotation;
  3. import java.lang.reflect.Method;
  4. public class SimpleAccessAnnotation {
  5. static void accessAnnotationTest(Class usingAnnnotationClass){
  6. try {
  7. //Object usingAnnnotationClass=Class.forName(usingAnnotationClassName).newInstance();
  8. Method [] methods=usingAnnnotationClass.getDeclaredMethods();//取得对方法
  9. for(Method method:methods){
  10. System.out.println(method.getName());
  11. SimpleAnnotation
  12. simpleAnnotation=method.getAnnotation(SimpleAnnotation.class);//得到方法的Annotation
  13. if(simpleAnnotation!=null){
  14. System.out.print(simpleAnnotation.value()+"==");
  15. String result=invoke(method,usingAnnnotationClass);
  16. System.out.println(result);
  17. }
  18. }
  19. } catch (Exception e) {
  20. // TODO Auto-generated catch block
  21. e.printStackTrace();
  22. }
  23. }
  24. static String invoke(Method m, Object o) {
  25. String result = "passed";
  26. try {
  27. m.invoke(m,new Object[]{});
  28. } catch (Exception e) {
  29. // TODO Auto-generated catch block
  30. result = "failed";
  31. }
  32. return result;
  33. }
  34. /**
  35. * @param args
  36. */
  37. public static void main(String[] args) {
  38. // TODO Auto-generated method stub
  39. accessAnnotationTest(UsingSimpleAnnotation.class);
  40. }
  41. }

<script type="text/javascript">render_code();</script>

Java 中的Annotation的定义

Java中的Annotation

Java定义了几个标准的meta-annotation,在新Package中java.lang.annotation 中包含了以下meta-annotation:

meta-annotation 说明

@Target

1. annotation的target是一个被标注的程序元素。target说明了annotation所修饰的对象范围:annotation可被用于packages、types(类、接口、枚举、annotation类型)、类型成员(方法、构造方法、成员变量、枚举值)、方法参数和本地变量(如循环变量、catch参数)。在annotation类型的声明中使用了target可更加明晰其修饰的目标。

meta-annotation 说明
@Target 1. annotation的target是一个被标注的程序元素。target说明了annotation所修饰的对象范围:annotation可被用于packages、types(类、接口、枚举、annotation类型)、类型成员(方法、构造方法、成员变量、枚举值)、方法参数和本地变量(如循环变量、catch参数)。在annotation类型的声明中使用了target可更加明晰其修饰的目标。

2. ElementType的定义

TYPE// Class, interface, or enum (but not annotation)
FIELD// Field (including enumerated values)

METHOD// Method (does not include constructors)

PARAMETER// Method parameter

CONSTRUCTOR// Constructor

LOCAL_VARIABLE// Local variable or catch clause

ANNOTATION_TYPE// Annotation Types (meta-annotations)

PACKAGE// Java package

@Retention

1. SOURCE//按照规定使用注释,但是并不将它保留到编译后的类文件中

2. CLASS//将注释保留在编译后的类文件中,但是在运行时忽略它

3. RUNTIME//将注释保留在编译后的类文件中,并在第一次加载类时读取它

@Documented Documented 表示注释应该出现在类的 Javadoc 中

@Inherited 一个Annotation将被继承

三个标准的Annotation 在java.lang包中:

@Deprecated 对不再使用的方法进行注释
@Override 指明注释的方法覆盖超类的方法
@SuppressWarnings 阻止编译器的警告,例:当类型不安全时

下例来说明这三个标准的Annotation:

代码
  1. package sz.starbex.bill.annotation;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. public class SimpleOverrideAnnotation {
  5. public static void main(String[] args) {
  6. SimpleOverrideAnnotation test = new SimpleOverrideAnnotation();
  7. System.out.println(test.toString());
  8. }
  9. @Override
  10. public String toString() {
  11. return "自己的类自己输出";
  12. }
  13. @Deprecated
  14. public void doSomething() {
  15. System.out.println("方法已过时" );
  16. }
  17. @SuppressWarnings(value={"unchecked"})
  18. public void testSuppressWarnings(){
  19. List testList=new ArrayList();
  20. testList.add("KKKK");//没有使用范型,类型不安全
  21. }
  22. }

<script type="text/javascript">render_code();</script>

二、Annotation使用实例

一个组合的Annotation,注释类的

a. 商标Annotation

代码
  1. package sz.starbex.bill.annotation;
  2. public @interface Trademark {
  3. String name();
  4. String owner();
  5. }

<script type="text/javascript">render_code();</script>

b.License的annotation

代码
  1. package sz.starbex.bill.annotation;
  2. import java.lang.annotation.*;
  3. @Retention(RetentionPolicy.RUNTIME)
  4. @Target({ElementType.TYPE, ElementType.PACKAGE})
  5. public @interface License {
  6. String name();
  7. String notice();
  8. boolean redistributable();
  9. Trademark[] trademarks();
  10. }

<script type="text/javascript">render_code();</script>

c.测试类

代码
  1. package sz.starbex.bill.annotation;
  2. @License(name="Bill",
  3. notice="许可证",
  4. redistributable=true,
  5. trademarks={@Trademark(name="Mercedes",owner="Swedish"),
  6. @Trademark(name="Daewoo",owner="Korean")
  7. }
  8. )
  9. public class TestLicenseAnnotation {
  10. public static void main(String[] args) {
  11. TestLicenseAnnotation test=new TestLicenseAnnotation();
  12. License license=test.getClass().getAnnotation(License.class);
  13. System.out.println("License发放人:"+license.name());
  14. System.out.println("License注意事项:"+license.notice());
  15. System.out.println("License许可:"+license.redistributable());
  16. Trademark [] marks=license.trademarks();
  17. for(Trademark mark:marks){
  18. System.out.println("商标名称:"+mark.name());
  19. System.out.println("商标的使用者:"+mark.owner());
  20. }
  21. }
  22. }

什么是annotations相关推荐

  1. Unable to complete the scan for annotations for web application

    2019独角兽企业重金招聘Python工程师标准>>> Unable to complete the scan for annotations for web application ...

  2. EffectiveJava(v3) - chapter5: Enums And Annotations

    Enums And Annotations Java中支持两种特殊的引用类型: 一种特殊的类, 枚举; 一种特殊的接口, 注释. 本章主要是讲如何高效地使用这两种类型. Introduce Effec ...

  3. expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.spring

    在Spring项目中自动想用注解的方式,在controller里面注入Service但是报错,错误信息如下: [WARNING] Exception encountered during contex ...

  4. R语言使用magick包的image_annotate函数在图片中添加文本标签信息、自定义文本标签内容的位置、色彩(Text annotations)

    R语言使用magick包的image_annotate函数在图片中添加文本标签信息.自定义文本标签内容的位置.色彩(Text annotations) 目录

  5. [Hibernate] - Annotations - One To One

    Hibernate annotation 一对一的两种实现: 1)幅表中有主表的主键ID做为引用 2)幅表的主键即为主表的ID hibernate.cfg.xml <?xml version=& ...

  6. DeepFashion: Powering Robust Clothes Recognition and Retrieval with Rich Annotations – CVPR 2016

    DeepFashion: Powering Robust Clothes Recognition and Retrieval with Rich Annotations – CVPR 2016 论文( ...

  7. 异常处理:SEVERE: Unable to process Jar entry [......]for annotations java.io.EOFException

    异常处理:SEVERE: Unable to process Jar entry [......]for annotations java.io.EOFException 参考文章: (1)异常处理: ...

  8. hibernate annotations和hbm.xml配置文件在spring中的并存配置

    因为整合了不同的系统,一套系统使用的是hibernate annotation,另一套系统使用的是hbm.xml 偷懒不想重构,又不想修改太多,所以决定整合hibernate annotations和 ...

  9. WebApi数据验证——编写自定义数据注解(Data Annotations)

    2019独角兽企业重金招聘Python工程师标准>>> 配合ModelState使用,关于使用方法,参考微软文档 https://docs.microsoft.com/en-us/a ...

  10. How those spring enable annotations work--转

    原文地址:http://blog.fawnanddoug.com/2012/08/how-those-spring-enable-annotations-work.html Spring's Java ...

最新文章

  1. WinSock网络编程基础(3)server
  2. 杀毒软件已经 OUT 了!未来 CPU 也可以检测病毒
  3. JVM逃逸分析(同步省略、标量替换、栈上分配)
  4. 关于C语言中递归的一点点小问题
  5. 前端学习(2050)vue之电商管理系统电商系统之实现node创建服务器
  6. 53 - II. 0~n-1中缺失的数字
  7. Redis的安装与使用
  8. LeetCode 451. 根据字符出现频率排序(Sort Characters By Frequency)
  9. 李迟2011年3月代码积累
  10. ARCGIS地理信息系统学习笔记001--认识ARCGIS
  11. ng-app一些使用
  12. 移动机器人综合性能对比分析
  13. Java 8 Stream 闪亮登场!
  14. 10本经典的管理学书籍推荐,关于管理学的书都在这里了
  15. 书家必备——容易寫錯用錯的繁體字一百例
  16. 中国大学MOOC C语言程序设计(大连理工大学) 课后编程题 第九周题解(个人向仅供参考)
  17. 联想u盘启动linux,联想thinkpad e335台式机bios设置u盘启动的方法
  18. Matplotlib的柱状图
  19. java打怪升级地图
  20. 一键GHOST是什么?

热门文章

  1. HTML5 自动聚焦 autofocus 属性
  2. 使用功耗分析仪,对一款LORA低功耗温度传感器进行功耗评测,评估温度传感器的待机时长,供参考。
  3. 关于网站性能优化,一张思维导图够了
  4. PHP中 die() 和 exit() 的区别
  5. android 系统
  6. 微信公众号页面分享、禁止分享和显示右上角菜单
  7. 风控策略的自动化生成-利用决策树分分钟生成上千条策略
  8. Win10 ntoskrnl.exe蓝屏解决
  9. LabVIEW AI视觉工具包(非NI Vision)下载与安装教程
  10. H5网页链接APP浏览器跳转小程序-邪少外链