自定义Annotation
来源:http://blog.csdn.net/lifetragedy/article/details/7394910
概念篇##
来看一个最简单的annotation示例
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyAnnotation1
{
String value();
}
- Annotation需要声明为@interface这样的东西
- @Target(ElementType.TYPE)代表这个annotation必须且一定要加在什么样的语句上面,例如
ElementType.TYPE代表此Annotation必须声明在public class Student{…}的上面,而不能写在任何的method{}(方法)或者是field(属性)的上方。- @Target: 表示该注解可以用于什么地方。可用ElementType枚举类型主要有:
- TYPE : 类、接口或enum声明
- FIELD: 域(属性)声明
- METHOD: 方法声明
- PARAMETER: 参数声明
- CONSTRUCTOR: 构造方法声明
- LOCAL_VARIABLE:局部变量声明
- ANNOTATION_TYPE:注释类型声明
- PACKAGE: 包声明
- @Target: 表示该注解可以用于什么地方。可用ElementType枚举类型主要有:
- Retention如果设为了RUNTIME,代表此annotation的具体实现可以在运行时用类反射来实现
我们看到了,annotation一般为一个@interface,也没啥具体的implementation(实现)
怎么实现这个annotation呢?类反射。- @Retention: 表示需要在什么级别保存该注解信息。可用RetentionPolicy枚举类型主要有:
- SOURCE: 注解将被编译器丢弃。
- CLASS: 注解在class文件中可能。但会被VM丢弃。
- RUNTIME: VM将在运行时也保存注解(如果需要通过反射读取注解,则
使用该值)。
- @Retention: 表示需要在什么级别保存该注解信息。可用RetentionPolicy枚举类型主要有:
- @Documented: 将此注解包含在Javadoc中。
上面这个MyAnnotation1.class文件包含一个值,下面来一个含有两个值的annotation
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyAnnotation2
{
String description();
boolean isAnnotation();
}
关键是来看这两个自定义annotation的用法:
@MyAnnotation1("this isannotation1")
public class AnnotationDemo
{
@MyAnnotation2(description = "this is annotation2", isAnnotation = true)
public void sayHello()
{
System.out.println("hello world!");
}
public static void main(String[] args)
{
new AnnotationDemo().sayHello();
}
}
如果把@MyAnnotation1与@MyAnnotation2的位置换一换,会怎么样?
eclipse会报The annotation @MyAnnotation2 is disallowed for this location
高级篇##
首先,网上的一些关于自定义annotation教程所举的例子都不太好!
就2个例子,然后一帮子人在那边到处COPY这两个例子然后到处转发,搞得来大家云里雾里一头雾水, 同时一群企业的面试官也就喜欢拿这个自定义annotation来作面试题,好像会个annotation就能给Senior software engineer了。
其实Annotation就是类反射加点枚举,比个数据结构里的冒泡排序还简单,没这么夸张,关键是例子举的不好,现在来看看下面这个例子。
通过例子来看一个简单的Annotation
Hibernate的机制是可能通过JAVA类然后逆向成数据库里的某个表,大家还记得吧?
比如说Student.java文件,如果你这样写:
@Table(name="T_STUDENT")
Public class Student{…}
代表这个类对应的数据库表叫T_STUDENT
public class Student
{
private String id = "";
@Id(init = 1)
public void setId(String id)
{
this.id = id;
}
}
就代表id这个field是一个主键,它的初始值为1。
好了,现在开始我们自己的例子,设有一CLASS叫Student,其中有三个fields:
private String name = "";
private int age = 0;
private String studentId = "";
相应的每一个field有一对的set, get方法
然后我在每个set方法上造一个annotation叫ValueBind的注解,其作用是:
只要set方法上带有ValueBind注解,它就会根据这个字段的类型把一个默认值,自动赋给Student类中相对应的field。
先来看一下Student类:
public class Student
{
private String name = "";
private int age = 0;
private String studentId = "";
public String getName()
{
return name;
}
@ValueBind(type=fieldType.STRING, value="aa")
public void setName(String name)
{
this.name = name;
}
public int getAge()
{
return age;
}
@ValueBind(type=fieldType.INT, value="11")
public void setAge(int age)
{
this.age = age;
}
public String getStudentId()
{
return studentId;
}
@ValueBind(type=fieldType.STRING, value="1")
public void setStudentId(String studentId)
{
this.studentId = studentId;
}
}
自定义一个ValueBind的Annotation,这个@ValueBoind就是我的自定义的annotation,里面有两个值,来看这个annotation是怎么做的吧:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ValueBind
{
enum fieldType{
STRING, INT
}
fieldType type();
String value();
}
够简单的吧!
首先这个annotation只能被标注在方法上
其次它含有两个值,一个是enum类型,一个是String类型
利用JAVA类反射来实现我们的Annotation###
现在来看我们真正的实现(用类反射来实现)
public class PersistStudent
{
public static void main(String[] args) throws Exception
{
Object c = Class.forName("annotation.Student").newInstance();
try
{
Method[] methodArray = c.getClass().getDeclaredMethods();
for (int i = 0; i < methodArray.length; i++)
{
if (methodArray[i].isAnnotationPresent(ValueBind.class))
{
ValueBind annotation = methodArray[i].getAnnotation(ValueBind.class);
String type = String.valueOf(annotation.type());
String value = annotation.value();
if (type.equals("INT"))
{
methodArray[i].invoke(c, new Object[] { new Integer(value) });
}
else
{
methodArray[i].invoke(c, new Object[] { value });
}
}
}
Student annotaedStudent = (Student) c;
System.out.println("studentId====" + annotaedStudent.getStudentId() + " studentnName====" + annotaedStudent.getName() + " student Age====" + annotaedStudent.getAge());
}
catch (Exception e)
{
throw new Exception(e);
}
}
}
运行完毕后显示:
studentId == 1 studentnName == aa student Age ==11
自己把代码敲到eclipse里后再去感受一下吧,马上让你annotation入门
自定义Annotation的更多相关文章
- java自定义Annotation(载自百度文库)
java中自定义annotation需要@interface关键字和用到几个内置annotation. 用到的注解有@Target,@Retention,@Documented,@Inherited ...
- Java注解Annotation的用法 - 自定义Annotation实现
Java注解又称Java标注,是Java语言5.0版本开始支持加入源代码的特殊语法元数据. Java语言中的类.方法.变量.参数和包等都可以被标注.和Javadoc不同,Java标注可以通过反射获取标 ...
- Java自定义Annotation,通过反射解析Annotation
创建一个自定义的Annotation import java.lang.annotation.*; import java.lang.reflect.Method; @Documented @Targ ...
- Lombok自定义annotation扩展含Intellij插件
Lombok简介 Lombok(https://projectlombok.org/) 提供了以注解的形式为java对象增加属性和方法,这使得原来冗长的java源文件变的简洁(不需要再使用ide去生 ...
- 注解2 --- 自定义 Annotation --- 技术搬运工(尚硅谷)
定义新的 Annotation 类型使用 @interface 关键字 自定义注解自动继承了java.lang.annotation.Annotation接口 Annotation 的成员变量在 An ...
- springMVC的自定义annotation(@Retention@Target)详解
自定义注解: 使用@interface自定义注解时,自动继承了java.lang.annotation.Annotation接口,由编译程序自动完成其他细节.在定义注解时,不能继承其他的注解或接口.@ ...
- iOS高德地图自定义annotation添加不同图片
1.model类里面添加index #import <MAMapKit/MAMapKit.h> #import <AMapSearchKit/AMapCommonObj.h> ...
- springboot+redis+Interceptor+自定义annotation实现接口自动幂等
前言: 在实际的开发项目中,一个对外暴露的接口往往会面临很多次请求,我们来解释一下幂等的概念:任意多次执行所产生的影响均与一次执行的影响相同.按照这个含义,最终的含义就是 对数据库的影响只能是一次性的 ...
- 正确实现用spring扫描自定义的annotation
背景在使用spring时,有时候有会有一些自定义annotation的需求,比如一些Listener的回调函数. 比如: @Service public class MyService { @MyLi ...
随机推荐
- [课堂实践与项目]IOS优先级的计算器
这个计算器主要是使用数组进行实现的.虽然没有使用前缀后缀表达式,但是是一种方法o. .h文件 // // LCViewController.h // 具有优先级的calculator // // Cr ...
- JavaScript 进阶(一)JS的"多线程"
这个系列的文章名为“JavaScript 进阶”,内容涉及JS中容易忽略但是很有用的,偏JS底层的,以及复杂项目中的JS的实践.主要来源于我几年的开发过程中遇到的问题.小弟第一次写博客,写的不好的地方 ...
- Salt Stack 官方文档翻译 - 一个想做dba的sa - 博客频道 - CSDN.NET
OSNIT_百度百科 Salt Stack 官方文档翻译 - 一个想做dba的sa - 博客频道 - CSDN.NET Salt Stack 官方文档翻译 分类: 自动运维 2013-04-02 11 ...
- 编译android-4.3.1_r源代码并刷到自己的Galaxy Nexus I9250真机上
编译android-4.3.1_r源代码并刷到自己的Galaxy Nexus I9250真机上 作者:雨水 日期:2014-04-30 编译源码的目的还是为了自己改动源码,然后还可以执行在相应的手机 ...
- linux c编程 多线程(初级)《转载》---赠人玫瑰,手有余香!
原文地址:http://blog.csdn.net/liang890319/article/details/8393120 进程简单的说就是把一段代码复制成多份,并让他们同时执行.进程间通信是为了 ...
- jquery easyui Accordion的使用
<html> <head> <script src="jquery-easyui/jquery.min.js"></script> ...
- 9月mob(ShareSDK)活动预告,这个秋天非常热
9月秋天来临,广州的天气依旧非常热,广州的活动氛围更热~ 先有GMGC B2B对接会在广州创新谷,再有上方网TFC全球移动游戏开发人员大会来袭,游戏圈的火越烧越旺,成都GMGDC全球移动游戏开发人员大 ...
- 依赖注入(DI)有助于应用对象之间的解耦,而面向切面编程(AOP)有助于横切关注点与所影响的对象之间的解耦(转good)
依赖注入(DI)有助于应用对象之间的解耦,而面向切面编程(AOP)有助于横切关注点与所影响的对象之间的解耦.所谓横切关注点,即影响应用多处的功能,这些功能各个应用模块都需要,但又不是其主要关注点,常见 ...
- JavaScript引用类型之Object类
ECMAScript中的Object类跟Java中的Object类相似,ECMAScript中的全部类都由这个类继承而来,Object类中的全部属性和方法都会出如今其他类中,所以理解Object类,就 ...
- 解压tar.gz文件报错gzip: stdin: not in gzip format解决方法
解压tar.gz文件报错gzip: stdin: not in gzip format解决方法 在解压tar.gz文件的时候报错 1 2 3 4 5 [Sun@localhost Downloads] ...