Java注解提供关于代码的信息,并且对它们注解的代码没有直接的影响。在这篇教程中,我们将学习Java注解,如何自定义注解,注解用法和如何使用反射解析注解。

Java注解在Java1.5被引用并且在一些Java框架如Hibernate,Jersey,Spring中被广泛使用。注解是被嵌入到程序自身中的程序的元数据。它可以被注解解析工具或编译器解析。我们也可以指定注解的生命周期,或者仅在编译期间可用或者直到运行时。

在引入注解之前,我们可以通过程序注释或者Java文档来获取程序的元数据,但是注解提供的更多。它不仅包含元数据而且它能决定自身是否可用而且注解解析器可以使用它来控制处理流。

在Java中创建自定义注解

创建自定义注解类似于写一个接口,除了注解的接口关键字前多了一个@符号。我们可以在注解中声明方法。让我们看一个注解的例子然后再讨论它的特性。

package com.journaldev.annotations;

import java.lang.annotation.Documented;

import java.lang.annotation.ElementType;

import java.lang.annotation.Inherited;

import java.lang.annotation.Retention;

import java.lang.annotation.RetentionPolicy;

import java.lang.annotation.Target;

@Documented

@Target(ElementType.METHOD)

@Inherited

@Retention(RetentionPolicy.RUNTIME)

public @interface MethodInfo{

String author() default 'Pankaj';

String date();

int revision() default 1;

String comments();

}

注解方法不能有参数。

注解方法的返回值类型限于基本类型,String,Enums,Annotation或者上面这些的组合。

注解方法可以有默认值。

注解可以附加元数据。元注解可以提供关于这个注解的信息。

四种元注解:

1.@Documented-indicates that elements using this annotation should be documented by javadoc and similar tools. This type should be used to annotate the declarations of types whose annotations affect the use of annotated elements by their clients. If a type declaration is annotated with Documented, its annotations become part of the public API of the annotated elements.

2.@Target – indicates the kinds of program element to which an annotation type is applicable. Some possible values are TYPE, METHOD, CONSTRUCTOR, FIELD etc. If Target meta-annotation is not present, then annotation can be used on any program element.

3.@Inherited – indicates that an annotation type is automatically inherited. If user queries the annotation type on a class declaration, and the class declaration has no annotation for this type, then the class’s superclass will automatically be queried for the annotation type. This process will be repeated until an annotation for this type is found, or the top of the class hierarchy (Object) is reached.

4.@Retention – indicates how long annotations with the annotated type are to be retained. It takes RetentionPolicy argument whose Possible values are SOURCE, CLASS and RUNTIME

Java内置注解

Java提供三个内置注解:

1.@Override-当我们要重写父类的一个方法时,我们应该使用这个注解告诉编译器我们重写了这个方法。因此当父类的这个方法被移除或发生改变时,编译器将报错。

2.@Deprecated-当我们想让编译器知道一个方法已经过时时,我们应该这个注解。Java推荐将这个方法过时的原因以及它的替代方案写在Java文档中。

3.@SuppressWarnings-这个仅是用来告诉编译器忽略产生的特定警告,比如在泛型中使用原始类型。它的retention策略是SOURCE,所以它将被编译器丢弃。

让我们看一个使用Java内置注解和我们上面自定义的那个注解的一个例子:

package com.journaldev.annotations;

import java.io.FileNotFoundException;

import java.util.ArrayList;

import java.util.List;

public class AnnotationExample {

public static void main(String[] args) {

}

@Override

@MethodInfo(author = 'Pankaj', comments = 'Main method', date = 'Nov 17 2012', revision = 1)

public String toString() {

return 'Overriden toString method';

}

@Deprecated

@MethodInfo(comments = 'deprecated method', date = 'Nov 17 2012')

public static void oldMethod() {

System.out.println('old method, don't use it.');

}

@SuppressWarnings({ 'unchecked', 'deprecation' })

@MethodInfo(author = 'Pankaj', comments = 'Main method', date = 'Nov 17 2012', revision = 10)

public static void genericsTest() throws FileNotFoundException {

List l = new ArrayList();

l.add('abc');

oldMethod();

}

}

我相信这个例子大家都能够看的懂,它向我们展示了在不同情境下注解的使用。

Java注解解析

我们将使用反射从一个类中解析主解。请注意注解的Retention策略必须是RUNTIME,否则在运行时它的信息将失效,我们将得不到任何信息。

package com.journaldev.annotations;

import java.lang.annotation.Annotation;

import java.lang.reflect.Method;

public class AnnotationParsing {

public static void main(String[] args) {

try {

for (Method method : AnnotationParsing.class

.getClassLoader()

.loadClass(('com.journaldev.annotations.AnnotationExample'))

.getMethods()) {

// checks if MethodInfo annotation is present for the method

if (method

.isAnnotationPresent(com.journaldev.annotations.MethodInfo.class)) {

try {

// iterates all the annotations available in the method

for (Annotation anno : method.getDeclaredAnnotations()) {

System.out.println('Annotation in Method ''

+ method + '' : ' + anno);

}

MethodInfo methodAnno = method

.getAnnotation(MethodInfo.class);

if (methodAnno.revision() == 1) {

System.out.println('Method with revision no 1 = '

+ method);

}

} catch (Throwable ex) {

ex.printStackTrace();

}

}

}

} catch (SecurityException | ClassNotFoundException e) {

e.printStackTrace();

}

}

}

上面程序的输出为:

Annotation in Method 'public java.lang.String com.journaldev.annotations.AnnotationExample.toString()' : @com.journaldev.annotations.MethodInfo(author=Pankaj, revision=1, comments=Main method, date=Nov 17 2012)

Method with revision no 1 = public java.lang.String com.journaldev.annotations.AnnotationExample.toString()

Annotation in Method 'public static void com.journaldev.annotations.AnnotationExample.oldMethod()' : @java.lang.Deprecated()

Annotation in Method 'public static void com.journaldev.annotations.AnnotationExample.oldMethod()' : @com.journaldev.annotations.MethodInfo(author=Pankaj, revision=1, comments=deprecated method, date=Nov 17 2012)

Method with revision no 1 = public static void com.journaldev.annotations.AnnotationExample.oldMethod()

Annotation in Method 'public static void com.journaldev.annotations.AnnotationExample.genericsTest() throws java.io.FileNotFoundException' : @com.journaldev.annotations.MethodInfo(author=Pankaj, revision=10, comments=Main method, date=Nov 17 2012)

java注解教程 pdf_Java注解教程和自定义注解相关推荐

  1. java获取注解的属性值_反射+自定义注解,实现获取注解标记的属性

    目标:通过自定义注解 @Ignore 注解,觉得是否读取指定类的属性. 运行结果: [main] INFO util.FruitInfoUtil -水果的名字为:entity.Apple [main] ...

  2. 注解和反射详细笔记。自定义注解,元注解,内置注解。反射机制,Java Reflection,Java内存分析,反射操作注解,java.lang.reflect.Method,Class

    文章目录 注解 什么是注解 内置注解 元注解 自定义注解 反射机制 静态语言 vs 静态语言 Java Reflection 反射相关的主要API Class类 Java内存分析 创建运行时类的对象 ...

  3. java方法设置切点_如何通过自定义注解实现AOP切点定义

    面向切面编程(Aspect Oriented Programming, AOP)是面向对象编程(Object Oriented Programming,OOP)的强大补充,通过横切面注入的方式引入其他 ...

  4. Spring注解解析及工作原理、自定义注解

    注解(Annotation) 提供了一种安全的类似注释的机制,为我们在代码中添加信息提供了一种形式化得方法,使我们可以在稍后某个时刻方便的使用这些数据(通过解析注解来使用这些 数据),用来将任何的信息 ...

  5. Java注解详解以及如何实现自定义注解

    目录

  6. excel导出多重表头utils_Java中注解学习系列教程-4 使用自定义注解实现excel导出...

    本文是<Java中注解学习系列教程>第四篇文章也是小案例文章. 自定义注解小案例是:使用自定义注解实现excel导出. Excel导出分析: ​ 有表头.数据值.一般第一行是表头,从第二行 ...

  7. java 自定义注解 解析_java自定义注解

    1.Annotation的工作原理: JDK5.0中提供了注解的功能,允许开发者定义和使用自己的注解类型.该功能由一个定义注解类型的语法和描述一个注解声明的语法,读取注解的API,一个使用注解修饰的c ...

  8. 谈谈 Java 中自定义注解及使用场景

    点击上方"方志朋",选择"设为星标" 回复"666"获取新整理的面试文章 作者:快给我饭吃 www.jianshu.com/p/a7bedc ...

  9. 深入理解Java注解Annotation及自定义注解

    要深入学习注解,我们就必须能定义自己的注解,并使用注解,在定义自己的注解之前,我们就必须要了解Java为我们提供的元注解和相关定义注解的语法. 元注解: 元注解的作用就是负责注解其他注解.Java5. ...

  10. java 外部覆盖内部配置,Spring 与自定义注解、外部配置化的结合使用

    Spring 与自定义注解.外部配置化的结合使用 一.Java注解的简单介绍 注解,也叫Annotation.标注,是 Java 5 带来的新特性. 可使用范围 类.字段.方法.参数.构造函数.包等, ...

最新文章

  1. video 微信 标签层级过高_基于大数据的用户标签体系建设思路和应用
  2. 根据map中某一字段排序
  3. jQuery unbind 删除绑定事件 / 移除标签方法
  4. python dictwriter_手把手教你写爬虫 |Python 采集大众点评数据采集实战
  5. 最近在玩linux时 yum 遇到了问题
  6. 计算机体系结构课后答案
  7. 史上最强的下载器,没有之一
  8. python: 从pdf中提取图片
  9. 小水智能-智能楼宇智慧建筑3D可视化系统,为房屋建设增加智能化
  10. 基于深度学习的以图搜图
  11. erp实施 数据库面试题_erp实施顾问笔试题有什么_erp实施顾问笔试题
  12. 设CPU共有16根地址线,8根数据线,并用MREQ (低电平有效) .作访存控制信号,R/W作读写命令信号(高电平为读,,低电平为写)。
  13. Ubantu基础指令大集合
  14. python代码编辑器
  15. 线性表中的尾插法双链表的学习
  16. firnbsp;提交的版本的iphone4amp;nbs…
  17. 使用 JS 实现七彩雨
  18. 第12期《在速度与激情中奔跑》4月刊
  19. 吐槽我是特种兵之霹雳火
  20. 【Python】Python生成个性二维码

热门文章

  1. 高级openg 混合,一个完整程序
  2. 电脑老是弹出脱机连接_电脑在不联网的情况下.总是弹出脱机状态,是什么问题...
  3. 第三章:Windows 7操作——知识点整理
  4. ARM 反汇编工具objdump的使用简介
  5. i9 10900k用什么主板
  6. php 正则匹配http,php url正则表达式
  7. OL制服应该怎么画?衬衫正面、侧面、背面的绘画技巧
  8. 数字化转型导师坚鹏:美的集团数字化转型案例研究
  9. Android中如何把网络资源图片转化成bitmap
  10. 阿甘修理机器人cd_剑网3遗失的美好-剑网3遗失的美好换哪个好-剑网3遗失的美好可兑换物品一览_牛游戏网...