博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
四十一,java中Annotation详解
阅读量:7209 次
发布时间:2019-06-29

本文共 5876 字,大约阅读时间需要 19 分钟。

hot3.png

1.Annotation简介

Annotation实际上表示一种注释的语法,java中最早的程序是提倡代码与配置相分离,而最新的理论又是将所有的配置直接写入到程序中去,那么如果想要完成这样的功能,则需要使用Annotation.

JDK1.5之后的新特性:枚举,自动装箱拆箱,foreach,可变参数,静态导入,泛型.

2.系统内建的Annotation

  • @Override

  • @Deprecated

  • @SupressWarnings

2.1 @Override

@Override表示正确的覆写操作.

示例:

父类代码

public class Person {    public String say(){        return "人在说话。" ;    }}

子类代码 :
public class Studnt extends Person {    @Override    public String say(){        return "学生在说话" ;     }}

@Override可以保证正确的覆写,如果一个方法声明了覆写,而实际上覆写有问题就会提示出错误.

2.2 @Deprecated

@Deprecated表示不建议使用的操作.

示例:

public class Info {    @Deprecated    public String getInfo(){        return "hello" ;    }}
getInfo这个方法就是不建议使用的操作 ,在代码中会用中划线表示警告 ,但是不影响实际使用 .

2.3 @SupressWarnings

@SupressWarnings表示压制警告.

示例:

public class TestInfo {	@SuppressWarnings("deprecation")	public static void main(String[] args) {		new Info().getInfo() ;	}}
注意的是 SupressWarnings可以压制多个警告 .

示例:

import java.io.Serializable;@SuppressWarnings({ "serial", "deprecation" })public class Person extends Info implements Serializable {}

使用过程中,可以明确表示出是为 SuppressWarnings中的value属性赋值.

import java.io.Serializable;@SuppressWarnings(value = { "serial", "deprecation" })public class Person extends Info implements Serializable {}

3.自定义Annotation

定义Annotation的语法:

public @Annotation

示例:

public @interface MyAnnotation {    public String key() ;    public String value() ;}
现在如果要使用此 Annotation,不在同一个包中需要导入 ,导入之后使用 @Annotation的访问语法 .

示例:

@MyAnnotation(key = "ARES", value = "19")public class Info {}

注:可以为Annotation定义默认的属性.

public @interface MyAnnotation {	public String key() default "ARES";	public String value() default "19";}

Annotation可以通过枚举类型制定范围 .

示例:

Color类:

public enum Color {	RED, GREEN, BLUE;}
MyAnnotation类 :
public @interface MyAnnotation {	public String key() default "ARES";	public String value() default "19";	public Color color() default Color.RED ;}

4.Rentention和RententionPolicy

在java.lang.annotation中定义了所有与之相关的操作,Rentention本身是一个 Annotation,其中的取值是通过RententionPolicy这个枚举类型制定的.RententionPolicy规定了一下三种范围:

  • 源码中起作用:public static final RetentionPolicy SOURCE

  • 编译后的class中起作用:public static final RetentionPolicy CLASS

  • 运行的时候起作用:public static final RetentionPolicy RUNTIME

如果一个Annotation要起作用,则必须使用RUNTIME范围.

5.反射与Annotation

一个Annotation要想起作用,则必须依靠反射机制,通过反射机制可以取得一个方法在Annotation上声明的全部内容.

取得全部的Annotation.

示例:

import java.lang.annotation.*;@Retention(value=RetentionPolicy.RUNTIME)public @interface MyAnnotation {	public String key() default "ARES";	public String value();}

Info类:

package com.ares.demo;public class Info {	@Override	@Deprecated	@SuppressWarnings(value = "")	@MyAnnotation(key = "ARES", value = "19")	public String toString() {		return "hello";	}}
以上三个 Annotation,只有 @Deprecated 是 RUNTIME范围的 .所以运行时 ,只有运行时只有 @Deprecated 可以取到 .

示例:

package com.ares.demo;import java.lang.annotation.Annotation;import java.lang.reflect.Method;public class ClassAnnotationDemo {	public static void main(String[] args) throws Exception {		Class
cls = Class.forName("com.ares.demo.Info"); Method toStringMethod = cls.getMethod("toString"); Annotation ans[] = toStringMethod.getAnnotations();// 取得全部的Annotation for (int i = 0; i < ans.length; i++) { System.out.println(ans[i]) ; } }}

6.自定义RUNTIME的Annotation

示例:

package com.ares.demo12;import java.lang.annotation.*;@Documented@Target(value = { ElementType.METHOD, ElementType.TYPE })@Retention(value = RetentionPolicy.RUNTIME)public @interface MyAnnotation {	public String key() default "ARES";	public String value() default "ARES";}

通过反射取得Annotation:

package com.ares.demo;import java.lang.annotation.Annotation;import java.lang.reflect.Method;public class ClassAnnotationDemo {	public static void main(String[] args) throws Exception {		Class
cls = Class.forName("com.ares.demo.Info"); Method toStringMethod = cls.getMethod("toString"); Annotation ans[] = toStringMethod.getAnnotations();// 取得全部的Annotation for (int i = 0; i < ans.length; i++) { if (toStringMethod.isAnnotationPresent(MyAnnotation.class)) { MyAnnotation my = null; // 声明Annotation的对象 my = toStringMethod.getAnnotation(MyAnnotation.class) ; String key = my.key() ; String value = my.value() ; System.out.println(key + " --> " + value) ; } } } }

实际开发中不用过多关注这些底层的实现,程序中为其提供支持.

7.Annotation深入

①自定义Annotation可以在程序的任意位置使用.

示例:

package com.ares.demo;@MyAnnotationpublic class Info {	private String name ;	@MyAnnotation	public String toString() {		return "hello" ;	}}

注:实际上我们可以为Annotation制定使用范围.

②设置Annotation的使用范围.(实际有8种范围,可以查看手册)

制定范围示例:

package com.ares.demo;import java.lang.annotation.*;@Target(value = { ElementType.METHOD, ElementType.TYPE })@Retention(value = RetentionPolicy.RUNTIME)public @interface MyAnnotation {	public String key() default "ARES";	public String value() default "ARES";}

③Documented注释

注释格式:

package com.ares.demo;import java.lang.annotation.*;@Documented@Target(value = { ElementType.METHOD, ElementType.TYPE })@Retention(value = RetentionPolicy.RUNTIME)public @interface MyAnnotation {	public String key() default "ARES";	public String value() default "ARES";}

在使用类中加入文档注释:

package com.ares.demo;@MyAnnotationpublic class Info {	private String name ;	/**	 * 本方法是覆写Object类中的toString()方法	 */	@MyAnnotation	public String toString() {		return "hello" ;	}}

用文档注释的最大好处是可以导出doc文档.类似官方文档的html格式文档.

8.Inherited

表示此Annotation能否继续被子类继承下去,如果没有写上此注释,表示此Annotation根本就是无法被继承的.

示例:

package com.ares.demo;import java.lang.annotation.*;@Inherited@Documented@Target(value = { ElementType.METHOD, ElementType.TYPE })@Retention(value = RetentionPolicy.RUNTIME)public @interface MyAnnotation {	public String key() default "ARES";	public String value() default "ARES";}
此时表示可以被子类继承 .

20150529

JAVA学习笔记系列

--------------------------------------------

                    联系方式

--------------------------------------------

        Weibo: ARESXIONG

        E-Mail: aresxdy@gmail.com

------------------------------------------------

转载于:https://my.oschina.net/u/2288529/blog/421783

你可能感兴趣的文章
Hibernate中session.get()和session.load()的区别
查看>>
泊松分布(Poisson distribution)的简单认识
查看>>
Android之使用传感器获取相应数据
查看>>
Jquery中html()方法 and "click"绑定后代元素
查看>>
HashMap和Hashtable的详细区别
查看>>
virutalbox虚拟机硬盘扩容
查看>>
自学计划
查看>>
dp-01背包问题 (升级)
查看>>
MySQL数据库唯一性设置(unique index)
查看>>
Windows性能计数器(命令行方式)
查看>>
Perl information,doc,module document and FAQ.
查看>>
sql 查询目标数据库中所有的表以其关键信息
查看>>
linux 下安装tomcat
查看>>
集成xadmin源码到项目的正式姿势
查看>>
自定义ViewPager,避免左右滑动时与水平滑动控件冲突
查看>>
javaScript-进阶篇(一)
查看>>
截取地址栏参数
查看>>
Redis介绍及Jedis基础操作
查看>>
20061218: 多个任务管理器
查看>>
WCF 可靠会话
查看>>