-
深入JAVA注解(Annotation):自定义注解
2019-07-31 18:40:53一、基础知识:元注解 要深入学习注解,我们就必须能定义自己的注解,并使用注解...Java5.0定义了4个标准的meta-annotation类型,它们被用来提供对其它 annotation类型作说明。Java5.0定义的元注解: 1.@Targe...一、基础知识:元注解
要深入学习注解,我们就必须能定义自己的注解,并使用注解,在定义自己的注解之前,我们就必须要了解Java为我们提供的元注解和相关定义注解的语法。
元注解:
元注解的作用就是负责注解其他注解。Java5.0定义了4个标准的meta-annotation类型,它们被用来提供对其它 annotation类型作说明。Java5.0定义的元注解:
1.@Target,
2.@Retention,
3.@Documented,
4.@Inherited
这些类型和它们所支持的类在java.lang.annotation包中可以找到。下面我们看一下每个元注解的作用和相应分参数的使用说明。@Target:
@Target说明了Annotation所修饰的对象范围:Annotation可被用于 packages、types(类、接口、枚举、Annotation类型)、类型成员(方法、构造方法、成员变量、枚举值)、方法参数和本地变量(如循环变量、catch参数)。在Annotation类型的声明中使用了target可更加明晰其修饰的目标。
作用:用于描述注解的使用范围(即:被描述的注解可以用在什么地方)
取值(ElementType)有:
1.CONSTRUCTOR:用于描述构造器
2.FIELD:用于描述域
3.LOCAL_VARIABLE:用于描述局部变量
4.METHOD:用于描述方法
5.PACKAGE:用于描述包
6.PARAMETER:用于描述参数
7.TYPE:用于描述类、接口(包括注解类型) 或enum声明使用实例:
@Target(ElementType.TYPE) public @interface Table { /** * 数据表名称注解,默认值为类名称 * @return */ public String tableName() default "className"; } @Target(ElementType.FIELD) public @interface NoDBColumn { }
注解Table 可以用于注解类、接口(包括注解类型) 或enum声明,而注解NoDBColumn仅可用于注解类的成员变量。
@Retention:
@Retention定义了该Annotation被保留的时间长短:某些Annotation仅出现在源代码中,而被编译器丢弃;而另一些却被编译在class文件中;编译在class文件中的Annotation可能会被虚拟机忽略,而另一些在class被装载时将被读取(请注意并不影响class的执行,因为Annotation与class在使用上是被分离的)。使用这个meta-Annotation可以对 Annotation的“生命周期”限制。
作用:表示需要在什么级别保存该注释信息,用于描述注解的生命周期(即:被描述的注解在什么范围内有效)
取值(RetentionPoicy)有:
1.SOURCE:在源文件中有效(即源文件保留)
2.CLASS:在class文件中有效(即class保留)
3.RUNTIME:在运行时有效(即运行时保留)Retention meta-annotation类型有唯一的value作为成员,它的取值来自java.lang.annotation.RetentionPolicy的枚举类型值。具体实例如下:
@Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface Column { public String name() default "fieldName"; public String setFuncName() default "setField"; public String getFuncName() default "getField"; public boolean defaultDBValue() default false; }
Column注解的的RetentionPolicy的属性值是RUTIME,这样注解处理器可以通过反射,获取到该注解的属性值,从而去做一些运行时的逻辑处理
@Documented:
@Documented用于描述其它类型的annotation应该被作为被标注的程序成员的公共API,因此可以被例如javadoc此类的工具文档化。Documented是一个标记注解,没有成员。
@Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Column { public String name() default "fieldName"; public String setFuncName() default "setField"; public String getFuncName() default "getField"; public boolean defaultDBValue() default false; }
@Inherited:
@Inherited 元注解是一个标记注解,@Inherited阐述了某个被标注的类型是被继承的。如果一个使用了@Inherited修饰的annotation类型被用于一个class,则这个annotation将被用于该class的子类。
注意:@Inherited annotation类型是被标注过的class的子类所继承。类并不从它所实现的接口继承annotation,方法并不从它所重载的方法继承annotation。
当@Inherited annotation类型标注的annotation的Retention是RetentionPolicy.RUNTIME,则反射API增强了这种继承性。如果我们使用java.lang.reflect去查询一个@Inherited annotation类型的annotation时,反射代码检查将展开工作:检查class和其父类,直到发现指定的annotation类型被发现,或者到达类继承结构的顶层。
实例代码:
/** * * @author peida * */ @Inherited public @interface Greeting { public enum FontColor{ BULE,RED,GREEN}; String name(); FontColor fontColor() default FontColor.GREEN; }
二、基础知识:自定义注解
使用@interface自定义注解时,自动继承了java.lang.annotation.Annotation接口,由编译程序自动完成其他细节。在定义注解时,不能继承其他的注解或接口。@interface用来声明一个注解,其中的每一个方法实际上是声明了一个配置参数。方法的名称就是参数的名称,返回值类型就是参数的类型(返回值类型只能是基本类型、Class、String、enum)。可以通过default来声明参数的默认值。
定义注解格式:
public @interface 注解名 {定义体}注解参数的可支持数据类型:
1.所有基本数据类型(int,float,boolean,byte,double,char,long,short)
2.String类型
3.Class类型
4.enum类型
5.Annotation类型
6.以上所有类型的数组Annotation类型里面的参数该怎么设定:
第一,只能用public或默认(default)这两个访问权修饰.例如,String value();这里把方法设为defaul默认类型;
第二,参数成员只能用基本类型byte,short,char,int,long,float,double,boolean八种基本数据类型和 String,Enum,Class,annotations等数据类型,以及这一些类型的数组.例如,String value();这里的参数成员就为String;
第三,如果只有一个参数成员,最好把参数名称设为"value",后加小括号.例:下面的例子FruitName注解就只有一个参数成员。简单的自定义注解和使用注解实例:
package annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 水果名称注解 * @author peida * */ @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface FruitName { String value() default ""; }
package annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 水果颜色注解 * @author peida * */ @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface FruitColor { /** * 颜色枚举 * @author peida * */ public enum Color{ BULE,RED,GREEN}; /** * 颜色属性 * @return */ Color fruitColor() default Color.GREEN; }
package annotation; import annotation.FruitColor.Color; public class Apple { @FruitName("Apple") private String appleName; @FruitColor(fruitColor=Color.RED) private String appleColor; public void setAppleColor(String appleColor) { this.appleColor = appleColor; } public String getAppleColor() { return appleColor; } public void setAppleName(String appleName) { this.appleName = appleName; } public String getAppleName() { return appleName; } public void displayName(){ System.out.println("水果的名字是:苹果"); } }
注解元素的默认值:
注解元素必须有确定的值,要么在定义注解的默认值中指定,要么在使用注解时指定,非基本类型的注解元素的值不可为null。因此, 使用空字符串或0作为默认值是一种常用的做法。这个约束使得处理器很难表现一个元素的存在或缺失的状态,因为每个注解的声明中,所有元素都存在,并且都具有相应的值,为了绕开这个约束,我们只能定义一些特殊的值,例如空字符串或者负数,一次表示某个元素不存在,在定义注解时,这已经成为一个习惯用法。
三、自定义注解实例
以上都是一些注解的基础知识,这里讲一下自定义注解的使用。一般,注解都是搭配反射的解析器共同工作的,然后利用反射机制查看类的注解内容。如下:
1 package testAnnotation; 2 3 import java.lang.annotation.Documented; 4 import java.lang.annotation.Retention; 5 import java.lang.annotation.RetentionPolicy; 6 7 @Documented 8 @Retention(RetentionPolicy.RUNTIME) 9 public @interface Person{ 10 String name(); 11 int age(); 12 }
package testAnnotation; 2 3 @Person(name="xingoo",age=25) 4 public class test3 { 5 public static void print(Class c){ 6 System.out.println(c.getName()); 7 8 //java.lang.Class的getAnnotation方法,如果有注解,则返回注解。否则返回null 9 Person person = (Person)c.getAnnotation(Person.class); 10 11 if(person != null){ 12 System.out.println("name:"+person.name()+" age:"+person.age()); 13 }else{ 14 System.out.println("person unknown!"); 15 } 16 } 17 public static void main(String[] args){ 18 test3.print(test3.class); 19 } 20 }
运行结果:
testAnnotation.test3 name:xingoo age:25
接下来再讲一个工作中的例子就可以收篇啦!
LoginVerify注解是用于对标注的方法在进行请求访问时进行登录判断。
package com.newsee.annotation; 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 LoginVerify { }
ScanningLoginVerifyAnnotation里的scanning()方法被@PostConstruct修饰,说明它在服务器加载Servlet的时候运行,并且只会被服务器执行一次。
这里再科普一下:
@PostConstruct和@PreDestroy。这两个注解被用来修饰一个非静态的void()方法 。写法有如下两种方式:
@PostConstruct
Public void someMethod() {}
或者public @PostConstruct void someMethod(){}
被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器执行一次。PostConstruct会在构造函数之后,init()方法之前执行。PreDestroy()方法在destroy()方法执行之后执行
scanning方法是在servlet加载完毕后获取所有被加载类,遍历其中的方法,如果有被LoginVerify注解修饰,则该方法名放到一个static的map中存储起来。
package com.newsee.annotation; import java.io.IOException; import java.lang.reflect.Method; import javax.annotation.PostConstruct; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.core.io.support.ResourcePatternResolver; import org.springframework.stereotype.Component; import org.springframework.util.ClassUtils; import com.newsee.constant.LoginVerifyMapping; @Component public class ScanningLoginVerifyAnnotation { private static final String PACKAGE_NAME = "com.newsee.face"; private static final String RESOURCE_PATTERN = "/**/*.class"; @PostConstruct public void scanning() throws IOException, SecurityException, ClassNotFoundException { String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + ClassUtils.convertClassNameToResourcePath(PACKAGE_NAME) + RESOURCE_PATTERN; ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(); Resource[] resources = resourcePatternResolver.getResources(pattern); for (Resource resource : resources) { if (resource.isReadable()) { String className = getClassName(resource.getURL().toString()); Class cls = ScanningRequestCodeAnnotation.class.getClassLoader().loadClass((className)); for (Method method : cls.getMethods()) { LoginVerify requestCode = method.getAnnotation(LoginVerify.class); if (requestCode != null) { </span>LoginVerifyMapping.add(className + "."+ method.getName()); } } } } } private String getClassName(String resourceUrl) { String url = resourceUrl.replace("/", "."); url = url.replace("\\", "."); url = url.split("com.newsee")[1]; url = url.replace(".class", ""); return "com.newsee" + url.trim(); } }
LoginVerifyMapping就是存放被LoginVerify注解修饰的方法名的。
public class LoginVerifyMapping { private static Map<String, Boolean> faceFunctionIsNeedLoginVerify = new HashMap<String, Boolean>(); public static void add(String functionName) { faceFunctionIsNeedLoginVerify.put(functionName, Boolean.TRUE); } public static Boolean getFaceFunctionIsNeedLoginVerify(String functionName) { return faceFunctionIsNeedLoginVerify.get(functionName); } }
以下方法就是请求过来时判断请求的方法是不是在LoginVerifyMapping中,如果是,则需要进行登录校验。
private ResponseContent handleRequests(RequestContent requestContent) throws ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { String requestCode = requestContent.getRequest().getHead().getNWCode(); String className = RequestCodeMapping.getClassName(requestCode); String beanName = RequestCodeMapping.getBeanName(requestCode); String functionName = RequestCodeMapping.getFunctionName(requestCode); Boolean loginVerify = LoginVerifyMapping.getFaceFunctionIsNeedLoginVerify(className + "." + functionName); if (loginVerify != null && loginVerify) {//需要进行登录校验 boolean isAuthenticated = SecurityUtils.getSubject().isAuthenticated(); if (!isAuthenticated) { String exId=requestContent.getRequest().getHead().getNWExID(); SystemMobileTokenKeyServiceInter systemMobileTokenKeyServiceInter = (SystemMobileTokenKeyServiceInter) SpringContextUtil .getBean("systemMobileTokenKeyServiceInter"); SystemMobileTokenKey systemMobileTokenKey=systemMobileTokenKeyServiceInter.getByExId(exId); if(systemMobileTokenKey==null) throw new BaseException(ResponseCodeEnum.NO_LOGIN); Date keyTime = systemMobileTokenKey.getKeyTime(); if (System.currentTimeMillis() - keyTime.getTime() > 1000 * 60 * 60 * 24 * 3) throw new BaseException(ResponseCodeEnum.NO_LOGIN); } } if (className == null || beanName == null || functionName == null) throw new BaseException(ResponseCodeEnum.REQUEST_CODE_NOT_EXIST); Object object = SpringContextUtil.getBean(beanName); Class cls = Class.forName(className); Method method = cls.getMethod(functionName, RequestContent.class); Object response = method.invoke(object, requestContent); return (ResponseContent) response; } }
-
Annotation
2018-08-28 16:33:38Annotation称为注释或注解,它是一个接口。注解提供了一种为程序元素(类、方法、成员变量等)设置元数据(描述其它数据的数据)的方法。编译器、开发工具或其它程序中可以通过反射来获取程序中的Annotation对象,...Annotation称为注释或注解,它是一个接口。注解提供了一种为程序元素(类、方法、成员变量等)设置元数据(描述其它数据的数据)的方法。编译器、开发工具或其它程序中可以通过反射来获取程序中的Annotation对象,通过该对象获得注解里的元数据。注解不影响程序代码,通过使用注解可以在不改变程序逻辑的情况下,在源文件中嵌入一些补充信息。
1、基本注释
@Override:表明该方法是重写父类的方法,或者是实现接口的方法,eg:
class Test { @Override public void func() { ...... } }
@Deprecated:表示该类或方法已过时被弃用,程序使用这些类或方法时会发出编译警告。
@SuppressWarnings:指示类或方法取消显示的编译警告,@SuppressWarnings中只有一个类型为String[]的元素成员value,其中常见的参数值为:
1.deprecation:使用了不赞成使用的类或方法时的警告;
2.unchecked:执行了未检查的转换时的警告,例如当使用集合时没有用泛型 (Generics) 来指定集合保存的类型;
3.fallthrough:当 Switch 程序块直接通往下一种情况而没有 Break 时的警告;
4.path:在类路径、源文件路径等中有不存在的路径时的警告;
5.serial:当在可序列化的类上缺少 serialVersionUID 定义时的警告;
6.finally:任何 finally 子句不能正常完成时的警告;
7.all:关于以上所有情况的警告。使用示例:
@SuppressWarnings(value="unchecked") public void func1() { List list = new ArrayList<Integer>(); list.add(10); //list没有指定泛型,此处会产生警告 List<String> ls = list; //将不带泛型的对象赋给带泛型的对象,产生警告,导致“堆污染” System.out.println(ls.get(0));//该语句运行时产生异常 } @SuppressWarnings({"unchecked", "deprecation"}) public void func2() { }
@SafeVarargs:指示取消显示个数可变形参产生的警告,eg:
@SafeVarargs public static void func3(List<String>...aryStringList) //个数可变的形参相当于是数组,因为没有泛型数组,所以形参相当于是一个List[],泛型被抹去,产生“堆污染” { }
@FunctionalInterface:指示该接口是一个函数式接口(只有一个抽象方法,可以包含多个默认方法或静态方法的接口)。如Runnable接口:
2、自定义注释
使用@interface来自定义一个注解,如下定义了名为Coder的注解,注解中包含两个元素personId(int类型)和company(String类型,默认值为"peking"):
public @interface Coder { int personId(); String city()default "peking"; }
如果注释中仅包含一个元素,这个元素的名字应该为value,如:
public @interface Coder { String value(); }
注释中可以包含枚举类型:
public @interface FruitColor { public enum Color{ BULE,RED,GREEN}; //枚举 Color CoderColor() default Color.GREEN; }
声明(使用)自定义的注释的时候需要为其成员变量指定值,如果该变量无默认值的话:
@Coder(personId = 1001) public void func() { ...... }
如果注释中元素的名字为value,那么在使用这个注解的时候,元素的名字和等号都可以省略,例如:
@Coder(“value”) public void func() { ...... }
根据注解是否包含成员可以将注解分为标记注解(如@Override)和元注解(如@Retention)。
3、JDK的元注释
在java.lang.annotation下有6个元Annotation,其中@Repeatable用于定义重复注解,其余5个用来修饰自定义的注解。
@Retention:指定被修饰的Annotation保留的时间,通过指定其value成员变量的值:
//编译器把注释保存在class文件中,当运行java程序时,JVM不可获取注释信息,这是默认值。 @Retention(value = RetentionPolicy.CLASS) @interface Testable{} //编译器把注释保存在class文件中,当运行java程序时,JVM可以获取注释信息 //程序可以通过反射获取该注释 @Retention(value = RetentionPolicy.RUNTIME) @interface Testable{} //注释保存在源码中,编译器直接丢弃该注释。 @Retention(value = RetentionPolicy.SOURCE) @interface Testable{}
@Target:指定被修饰的Annotation能够修饰哪些程序单元,其成员value值常见的值有:
ElementType.TYPE为指定该Annotation可以修饰类、接口(包括注解)、枚举定义。
ElementType.CONSTRUCTOR为指定该Annotation只能修饰构造方法。
ElementType.METHOD为指定该Annotation只能修饰方法定义。
ElementType.FIELD为指定该Annotation只能修饰成员变量。@Documented:指定被修饰的Annotation将被javadoc工具提取成文档。
@Inherited:指定被修饰的Annotation具有继承性,使用该Annotation的类的子类自动继承该Annotation。
@Repeatable:在java 8之前,程序的元素(类、方法等)不能添加相同类型的注解,比如下面为使用两个@Result注解的实现方法:
@Results({@Result(name = "liyang"), @Result(name = "wulei")}) public void func() { }
java 8中允许使用多个相同类型的注解,通过为注解添加@Repeatable修饰。
4、使用自定义的注解
可以为类中某些方法实现注解,然后其他程序通过使用实现反射功能的API来读取该注解,通过该注解或注解中的成员来做对应的一些处理:
//Foo.java package xu; import java.lang.annotation.*; @Retention(value = RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @interface Testable { int id(); String city(); } public class Foo { public static void main (String[] args)throws Exception { } @Testable(id = 1001, city = "peking") public static void func() { System.out.println("func called"); } }
//Test.java package xu; import java.lang.annotation.*; import java.lang.reflect.Method; public class Test { public static void main (String[] args)throws Exception { //Class<?> cls = Class.forName("xu.Foo"); //获取类的class对象 //getMethod()获得类中指定方法,getMethods()获得类中所有方法。 for(Method m : Class.forName("xu.Foo").getMethods()) { if(m.isAnnotationPresent(Testable.class)) //如果该方法使用了Testable注解 { m.invoke(null); //调用该方法 } } //getAnnotation获得指定注解,getAnnotations获得所有注解 Annotation[] ary1 = Class.forName("xu.Foo").getMethod("func").getAnnotations(); for(Annotation tag : ary1)//输出Foo类中func方法的所有注解 { System.out.println(tag); } //Foo tt = (Foo)cls.getDeclaredConstructor().newInstance(); //获取Foo类的实例 Foo tt = new Foo(); Annotation[] ary2 = tt.getClass().getMethod("func").getAnnotations(); for(Annotation tag : ary1)//获取tt对象的func方法的所有注解的元数据 { if(tag instanceof Testable) { int id = ((Testable)tag).id(); String city = ((Testable)tag).city(); System.out.println(city + id); } } } } /* */
5、类型注解
java 8中对@Target的成员value的值增加了ElementType.TYPE_USE,它被称作类型注解,指定被修饰的注解除了在定义程序元素(类、接口、方法、成员变量)时使用,还可以在任何用到类型的地方使用,如使用new创建对象、类型转换、使用implements实现接口、使用throws声明抛出异常的时候:
@Target(ElementType.TYPE_USE) @interface notNull{} @notNull class Type implements @notNull Serializable { public void func1()//throws @notNull FileNotFoundException { Object obj = "fkjava.org"; String str = (@NotNull String)obj; Object win = new @NotNull JFrame("test"); } public void func2(List<@NotNull String> info){} }
6、APT
APT(Annotation Processing Tool)是一种注解处理工具,它能够提取出源文件中包含的注解信息,然后针对注解信息进行额外的处理。Annotation处理器通常会采用继承AbstractProcessor的方式来实现处理过程。javac命令中有一个-processor选项,它用来指定编译的时候使用指定的Annotation处理器提取并处理源文件中的注解。
-
annotation
2010-12-21 22:12:00Annotation在java的世界正铺天盖地展开,有空写这一篇简单的annotations的文章,算是关于Annotation入门的文章吧,希望能各位们能抛砖,共同学习...... 不讲废话了,实践才是硬道理. <br /> 第一...Annotation在java的世界正铺天盖地展开,有空写这一篇简单的annotations的文章,算是关于Annotation入门的文章吧,希望能各位们能抛砖,共同学习......
不讲废话了,实践才是硬道理.
第一部分:了解一下java1.5起默认的三个annotation类型:
一个是@Override:只能用在方法之上的,用来告诉别人这一个方法是改写父类的。
一个是@Deprecated:建议别人不要使用旧的API的时候用的,编译的时候会用产生警告信息,可以设定在程序里的所有的元素上.
一个是@SuppressWarnings:这一个类型可以来暂时把一些警告信息消息关闭.
如果不清楚上面三个类型的具体用法,各位可以baidu或google一下的,很简单的。
第二部分:讲一下annotation的概念先,再来讲一下怎样设计自己的annotation.
首先在jdk自带的java.lang.annotation包里,打开如下几个源文件:
1、源文件Target.java- @Documented
- @Retention(RetentionPolicy.RUNTIME)
- @Target(ElementType.ANNOTATION_TYPE)
- public @interface Target {
- ElementType[] value();
- }
@Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.ANNOTATION_TYPE) public @interface Target { ElementType[] value(); }
其中的@interface是一个关键字,在设计annotations的时候必须把一个类型定义为@interface,而不能用class或interface关键字(会不会觉得sun有点吝啬,偏偏搞得与interface这么像).
2、源文件Retention.java- @Documented
- @Retention(RetentionPolicy.RUNTIME)
- @Target(ElementType.ANNOTATION_TYPE)
- public @interface Retention {
- RetentionPolicy value();
- }
@Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.ANNOTATION_TYPE) public @interface Retention { RetentionPolicy value(); }
看到这里,大家可能都模糊了,都不知道在说什么,别急,往下看一下.
在上面的文件都用到了RetentionPolicy,ElementType这两个字段,你可能就会猜到这是两个java文件.的确,这两个文件的源代码如下:
3、源文件RetentionPolicy.java- public enum RetentionPolicy {
- SOURCE,
- CLASS,
- RUNTIME
- }
public enum RetentionPolicy { SOURCE, CLASS, RUNTIME }
这是一个enum类型,共有三个值,分别是SOURCE,CLASS 和 RUNTIME.
SOURCE代表的是这个Annotation类型的信息只会保留在程序源码里,源码如果经过了编译之后,Annotation的数据就会消失,并不会保留在编译好的.class文件里面。
ClASS的意思是这个Annotation类型的信息保留在程序源码里,同时也会保留在编译好的.class文件里面,在执行的时候,并不会把这一些信息加载到虚拟机(JVM)中去.注意一下,当你没有设定一个Annotation类型的Retention值时,系统默认值是CLASS.
第三个,是RUNTIME,表示在源码、编译好的.class文件中保留信息,在执行的时候会把这一些信息加载到JVM中去的.
举一个例子,如@Override里面的Retention设为SOURCE,编译成功了就不要这一些检查的信息;相反,@Deprecated里面的Retention设为RUNTIME,表示除了在编译时会警告我们使用了哪个被Deprecated的方法,在执行的时候也可以查出该方法是否被Deprecated.
4、源文件ElementType.java- public enum ElementType {
- TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR,
- LOCAL_VARIABLE, ANNOTATION_TYPE,PACKAGE
- }
public enum ElementType { TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE, ANNOTATION_TYPE,PACKAGE }
@Target里面的ElementType是用来指定Annotation类型可以用在哪一些元素上的.说明一下:TYPE(类型), FIELD(属性), METHOD(方法), PARAMETER(参数), CONSTRUCTOR(构造函数),LOCAL_VARIABLE(局部变量), ANNOTATION_TYPE,PACKAGE(包),其中的TYPE(类型)是指可以用在Class,Interface,Enum和Annotation类型上.
另外,从1的源代码可以看出,@Target自己也用了自己来声明自己,只能用在ANNOTATION_TYPE之上.
如果一个Annotation类型没有指明@Target使用在哪些元素上,那么它可以使用在任何元素之上,这里的元素指的是上面的八种类型.
举几个正确的例子:
@Target(ElementType.METHOD)
@Target(value=ElementType.METHOD)
@Target(ElementType.METHOD,ElementType.CONSTRUCTOR)
具体参考一下javadoc文档
上面一下1和2的源文件,它们都使用了@Documented,@Documented的目的就是让这一个Annotation类型的信息能够显示在javaAPI说明文档上;没有添加的话,使用javadoc生成API文档的时候就会找不到这一个类型生成的信息.
另外一点,如果需要把Annotation的数据继承给子类,那么就会用到@Inherited这一个Annotation类型.
第三部分:下面讲的设计一个最简单的Annotation例子,这一例子共用四个文件;
1、Description.java- package lighter.javaeye.com;
- import java.lang.annotation.Documented;
- import java.lang.annotation.ElementType;
- import java.lang.annotation.Retention;
- import java.lang.annotation.RetentionPolicy;
- import java.lang.annotation.Target;
- @Target(ElementType.TYPE)
- @Retention(RetentionPolicy.RUNTIME)
- @Documented
- public @interface Description {
- String value();
- }
package lighter.javaeye.com; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Description { String value(); }
说明:所有的Annotation会自动继承java.lang.annotation这一个接口,所以不能再去继承别的类或是接口.
最重要的一点,Annotation类型里面的参数该怎么设定:
第一,只能用public或默认(default)这两个访问权修饰.例如,String value();这里把方法设为defaul默认类型.
第二,参数成员只能用基本类型byte,short,char,int,long,float,double,boolean八种基本数据类型和String,Enum,Class,annotations等数据类型,以及这一些类型的数组.例如,String value();这里的参数成员就为String.
第三,如果只有一个参数成员,最好把参数名称设为"value",后加小括号.例:上面的例子就只有一个参数成员.
2、Name.java- package lighter.javaeye.com;
- import java.lang.annotation.Documented;
- import java.lang.annotation.ElementType;
- import java.lang.annotation.Retention;
- import java.lang.annotation.RetentionPolicy;
- import java.lang.annotation.Target;
- //注意这里的@Target与@Description里的不同,参数成员也不同
- @Target(ElementType.METHOD)
- @Retention(RetentionPolicy.RUNTIME)
- @Documented
- public @interface Name {
- String originate();
- String community();
- }
package lighter.javaeye.com; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; //注意这里的@Target与@Description里的不同,参数成员也不同 @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Name { String originate(); String community(); }
3、JavaEyer.java- package lighter.javaeye.com;
- @Description("javaeye,做最棒的软件开发交流社区")
- public class JavaEyer {
- @Name(originate="创始人:robbin",community="javaEye")
- public String getName()
- {
- return null;
- }
- @Name(originate="创始人:江南白衣",community="springside")
- public String getName2()
- {
- return "借用两位的id一用,写这一个例子,请见谅!";
- }
- }
package lighter.javaeye.com; @Description("javaeye,做最棒的软件开发交流社区") public class JavaEyer { @Name(originate="创始人:robbin",community="javaEye") public String getName() { return null; } @Name(originate="创始人:江南白衣",community="springside") public String getName2() { return "借用两位的id一用,写这一个例子,请见谅!"; } }
4、最后,写一个可以运行提取JavaEyer信息的类TestAnnotation- package lighter.javaeye.com;
- import java.lang.reflect.Method;
- import java.util.HashSet;
- import java.util.Set;
- public class TestAnnotation {
- /**
- * author lighter
- * 说明:具体关天Annotation的API的用法请参见javaDoc文档
- */
- public static void main(String[] args) throws Exception {
- String CLASS_NAME = "lighter.javaeye.com.JavaEyer";
- Class test = Class.forName(CLASS_NAME);
- Method[] method = test.getMethods();
- boolean flag = test.isAnnotationPresent(Description.class);
- if(flag)
- {
- Description des = (Description)test.getAnnotation(Description.class);
- System.out.println("描述:"+des.value());
- System.out.println("-----------------");
- }
- //把JavaEyer这一类有利用到@Name的全部方法保存到Set中去
- Set<Method> set = new HashSet<Method>();
- for(int i=0;i<method.length;i++)
- {
- boolean otherFlag = method[i].isAnnotationPresent(Name.class);
- if(otherFlag) set.add(method[i]);
- }
- for(Method m: set)
- {
- Name name = m.getAnnotation(Name.class);
- System.out.println(name.originate());
- System.out.println("创建的社区:"+name.community());
- }
- }
- }
package lighter.javaeye.com; import java.lang.reflect.Method; import java.util.HashSet; import java.util.Set; public class TestAnnotation { /** * author lighter * 说明:具体关天Annotation的API的用法请参见javaDoc文档 */ public static void main(String[] args) throws Exception { String CLASS_NAME = "lighter.javaeye.com.JavaEyer"; Class test = Class.forName(CLASS_NAME); Method[] method = test.getMethods(); boolean flag = test.isAnnotationPresent(Description.class); if(flag) { Description des = (Description)test.getAnnotation(Description.class); System.out.println("描述:"+des.value()); System.out.println("-----------------"); } //把JavaEyer这一类有利用到@Name的全部方法保存到Set中去 Set<Method> set = new HashSet<Method>(); for(int i=0;i<method.length;i++) { boolean otherFlag = method[i].isAnnotationPresent(Name.class); if(otherFlag) set.add(method[i]); } for(Method m: set) { Name name = m.getAnnotation(Name.class); System.out.println(name.originate()); System.out.println("创建的社区:"+name.community()); } } }
5、运行结果:
描述:javaeye,做最棒的软件开发交流社区
-----------------
创始人:robbin
创建的社区:javaEye
创始人:江南白衣
创建的社区:springside
结论:1. annotation的作用:提供一种机制,将程序的元素如:类,方法,属性,参数,本地变量,包和元数据(数据的结构和意义的数据)联系
起来。这样编译器可以将元 数据存储在Class文件中。这样虚拟机和其它对象可以根据这些元数据来决定如何使用这些程序元素或改变
它们的行为。
2. 如何实现一个annotation:
a。用@Target 生命annotation的作用对象
b。用@Retention 生命annotation的存在范围。
c。用@interface 生命你的annotation
d。添加你的annotation方法()。
-
深入理解Java注解类型(@Annotation)
2017-05-21 10:51:43【版权申明】未经博主同意,谢绝转载!(请尊重原创,博主保留追究权) ... 出自【zejian的博客】 关联文章: 深入理解Java类型信息(Class对象)与反射机制 ...深入理解Java注解类型(@Annotation) 深入理解【版权申明】未经博主同意,谢绝转载!(请尊重原创,博主保留追究权)
http://blog.csdn.net/javazejian/article/details/71860633
出自【zejian的博客】关联文章:
java注解是在JDK5时引入的新特性,鉴于目前大部分框架(如Spring)都使用了注解简化代码并提高编码的效率,因此掌握并深入理解注解对于一个Java工程师是来说是很有必要的事。本篇我们将通过以下几个角度来分析注解的相关知识点
理解Java注解
实际上Java注解与普通修饰符(public、static、void等)的使用方式并没有多大区别,下面的例子是常见的注解:
public class AnnotationDemo { //@Test注解修饰方法A @Test public static void A(){ System.out.println("Test....."); } //一个方法上可以拥有多个不同的注解 @Deprecated @SuppressWarnings("uncheck") public static void B(){ } }
通过在方法上使用@Test注解后,在运行该方法时,测试框架会自动识别该方法并单独调用,@Test实际上是一种标记注解,起标记作用,运行时告诉测试框架该方法为测试方法。而对于@Deprecated和@SuppressWarnings(“uncheck”),则是Java本身内置的注解,在代码中,可以经常看见它们,但这并不是一件好事,毕竟当方法或是类上面有@Deprecated注解时,说明该方法或是类都已经过期不建议再用,@SuppressWarnings 则表示忽略指定警告,比如@SuppressWarnings(“uncheck”),这就是注解的最简单的使用方式,那么下面我们就来看看注解定义的基本语法
基本语法
声明注解与元注解
我们先来看看前面的Test注解是如何声明的:
//声明Test注解 @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface Test { }
我们使用了
@interface
声明了Test注解,并使用@Target
注解传入ElementType.METHOD
参数来标明@Test只能用于方法上,@Retention(RetentionPolicy.RUNTIME)
则用来表示该注解生存期是运行时,从代码上看注解的定义很像接口的定义,确实如此,毕竟在编译后也会生成Test.class文件。对于@Target
和@Retention
是由Java提供的元注解,所谓元注解就是标记其他注解的注解,下面分别介绍@Target 用来约束注解可以应用的地方(如方法、类或字段),其中ElementType是枚举类型,其定义如下,也代表可能的取值范围
public enum ElementType { /**标明该注解可以用于类、接口(包括注解类型)或enum声明*/ TYPE, /** 标明该注解可以用于字段(域)声明,包括enum实例 */ FIELD, /** 标明该注解可以用于方法声明 */ METHOD, /** 标明该注解可以用于参数声明 */ PARAMETER, /** 标明注解可以用于构造函数声明 */ CONSTRUCTOR, /** 标明注解可以用于局部变量声明 */ LOCAL_VARIABLE, /** 标明注解可以用于注解声明(应用于另一个注解上)*/ ANNOTATION_TYPE, /** 标明注解可以用于包声明 */ PACKAGE, /** * 标明注解可以用于类型参数声明(1.8新加入) * @since 1.8 */ TYPE_PARAMETER, /** * 类型使用声明(1.8新加入) * @since 1.8 */ TYPE_USE }
请注意,当注解未指定Target值时,则此注解可以用于任何元素之上,多个值使用{}包含并用逗号隔开,如下:
@Target(value={CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE})
@Retention用来约束注解的生命周期,分别有三个值,源码级别(source),类文件级别(class)或者运行时级别(runtime),其含有如下:
SOURCE:注解将被编译器丢弃(该类型的注解信息只会保留在源码里,源码经过编译后,注解信息会被丢弃,不会保留在编译好的class文件里)
CLASS:注解在class文件中可用,但会被VM丢弃(该类型的注解信息会保留在源码里和class文件里,在执行的时候,不会加载到虚拟机中),请注意,当注解未定义Retention值时,默认值是CLASS,如Java内置注解,@Override、@Deprecated、@SuppressWarnning等
RUNTIME:注解信息将在运行期(JVM)也保留,因此可以通过反射机制读取注解的信息(源码、class文件和执行的时候都有注解的信息),如SpringMvc中的@Controller、@Autowired、@RequestMapping等。
注解元素及其数据类型
通过上述对@Test注解的定义,我们了解了注解定义的过程,由于@Test内部没有定义其他元素,所以@Test也称为标记注解(marker annotation),但在自定义注解中,一般都会包含一些元素以表示某些值,方便处理器使用,这点在下面的例子将会看到:
/** * Created by wuzejian on 2017/5/18. * 对应数据表注解 */ @Target(ElementType.TYPE)//只能应用于类上 @Retention(RetentionPolicy.RUNTIME)//保存到运行时 public @interface DBTable { String name() default ""; }
上述定义一个名为DBTable的注解,该用于主要用于数据库表与Bean类的映射(稍后会有完整案例分析),与前面Test注解不同的是,我们声明一个String类型的name元素,其默认值为空字符,但是必须注意到对应任何元素的声明应采用方法的声明方式,同时可选择使用default提供默认值,@DBTable使用方式如下:
//在类上使用该注解 @DBTable(name = "MEMBER") public class Member { //....... }
关于注解支持的元素数据类型除了上述的String,还支持如下数据类型
所有基本类型(int,float,boolean,byte,double,char,long,short)
String
Class
enum
Annotation
上述类型的数组
倘若使用了其他数据类型,编译器将会丢出一个编译错误,注意,声明注解元素时可以使用基本类型但不允许使用任何包装类型,同时还应该注意到注解也可以作为元素的类型,也就是嵌套注解,下面的代码演示了上述类型的使用过程:
package com.zejian.annotationdemo; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Created by wuzejian on 2017/5/19. * 数据类型使用Demo */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @interface Reference{ boolean next() default false; } public @interface AnnotationElementDemo { //枚举类型 enum Status {FIXED,NORMAL}; //声明枚举 Status status() default Status.FIXED; //布尔类型 boolean showSupport() default false; //String类型 String name()default ""; //class类型 Class<?> testCase() default Void.class; //注解嵌套 Reference reference() default @Reference(next=true); //数组类型 long[] value(); }
编译器对默认值的限制
编译器对元素的默认值有些过分挑剔。首先,元素不能有不确定的值。也就是说,元素必须要么具有默认值,要么在使用注解时提供元素的值。其次,对于非基本类型的元素,无论是在源代码中声明,还是在注解接口中定义默认值,都不能以null作为值,这就是限制,没有什么利用可言,但造成一个元素的存在或缺失状态,因为每个注解的声明中,所有的元素都存在,并且都具有相应的值,为了绕开这个限制,只能定义一些特殊的值,例如空字符串或负数,表示某个元素不存在。
注解不支持继承
注解是不支持继承的,因此不能使用关键字extends来继承某个@interface,但注解在编译后,编译器会自动继承java.lang.annotation.Annotation接口,这里我们反编译前面定义的DBTable注解
package com.zejian.annotationdemo; import java.lang.annotation.Annotation; //反编译后的代码 public interface DBTable extends Annotation { public abstract String name(); }
虽然反编译后发现DBTable注解继承了Annotation接口,请记住,即使Java的接口可以实现多继承,但定义注解时依然无法使用extends关键字继承@interface。
快捷方式
所谓的快捷方式就是注解中定义了名为value的元素,并且在使用该注解时,如果该元素是唯一需要赋值的一个元素,那么此时无需使用key=value的语法,而只需在括号内给出value元素所需的值即可。这可以应用于任何合法类型的元素,记住,这限制了元素名必须为value,简单案例如下
package com.zejian.annotationdemo; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Created by zejian on 2017/5/20. * Blog : http://blog.csdn.net/javazejian [原文地址,请尊重原创] */ //定义注解 @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) @interface IntegerVaule{ int value() default 0; String name() default ""; } //使用注解 public class QuicklyWay { //当只想给value赋值时,可以使用以下快捷方式 @IntegerVaule(20) public int age; //当name也需要赋值时必须采用key=value的方式赋值 @IntegerVaule(value = 10000,name = "MONEY") public int money; }
Java内置注解与其它元注解
接着看看Java提供的内置注解,主要有3个,如下:
@Override:用于标明此方法覆盖了父类的方法,源码如下
@Target(ElementType.METHOD) @Retention(RetentionPolicy.SOURCE) public @interface Override { }
@Deprecated:用于标明已经过时的方法或类,源码如下,关于@Documented稍后分析:
@Documented @Retention(RetentionPolicy.RUNTIME) @Target(value={CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE}) public @interface Deprecated { }
@SuppressWarnnings:用于有选择的关闭编译器对类、方法、成员变量、变量初始化的警告,其实现源码如下:
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE}) @Retention(RetentionPolicy.SOURCE) public @interface SuppressWarnings { String[] value(); }
其内部有一个String数组,主要接收值如下:
deprecation:使用了不赞成使用的类或方法时的警告; unchecked:执行了未检查的转换时的警告,例如当使用集合时没有用泛型 (Generics) 来指定集合保存的类型; fallthrough:当 Switch 程序块直接通往下一种情况而没有 Break 时的警告; path:在类路径、源文件路径等中有不存在的路径时的警告; serial:当在可序列化的类上缺少 serialVersionUID 定义时的警告; finally:任何 finally 子句不能正常完成时的警告; all:关于以上所有情况的警告。
这个三个注解比较简单,看个简单案例即可:
//注明该类已过时,不建议使用 @Deprecated class A{ public void A(){ } //注明该方法已过时,不建议使用 @Deprecated() public void B(){ } } class B extends A{ @Override //标明覆盖父类A的A方法 public void A() { super.A(); } //去掉检测警告 @SuppressWarnings({"uncheck","deprecation"}) public void C(){ } //去掉检测警告 @SuppressWarnings("uncheck") public void D(){ } }
前面我们分析了两种元注解,@Target和@Retention,除了这两种元注解,Java还提供了另外两种元注解,@Documented和@Inherited,下面分别介绍:
@Documented 被修饰的注解会生成到javadoc中
/** * Created by zejian on 2017/5/20. * Blog : http://blog.csdn.net/javazejian [原文地址,请尊重原创] */ @Documented @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface DocumentA { } //没有使用@Documented @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface DocumentB { } //使用注解 @DocumentA @DocumentB public class DocumentDemo { public void A(){ } }
使用javadoc命令生成文档:
zejian@zejiandeMBP annotationdemo$ javadoc DocumentDemo.java DocumentA.java DocumentB.java
如下:
可以发现使用@Documented元注解定义的注解(@DocumentA)将会生成到javadoc中,而@DocumentB则没有在doc文档中出现,这就是元注解@Documented的作用。
@Inherited 可以让注解被继承,但这并不是真的继承,只是通过使用@Inherited,可以让子类Class对象使用getAnnotations()获取父类被@Inherited修饰的注解,如下:
@Inherited @Documented @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface DocumentA { } @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface DocumentB { } @DocumentA class A{ } class B extends A{ } @DocumentB class C{ } class D extends C{ } //测试 public class DocumentDemo { public static void main(String... args){ A instanceA=new B(); System.out.println("已使用的@Inherited注解:"+Arrays.toString(instanceA.getClass().getAnnotations())); C instanceC = new D(); System.out.println("没有使用的@Inherited注解:"+Arrays.toString(instanceC.getClass().getAnnotations())); } /** * 运行结果: 已使用的@Inherited注解:[@com.zejian.annotationdemo.DocumentA()] 没有使用的@Inherited注解:[] */ }
注解与反射机制
前面经过反编译后,我们知道Java所有注解都继承了Annotation接口,也就是说 Java使用Annotation接口代表注解元素,该接口是所有Annotation类型的父接口。同时为了运行时能准确获取到注解的相关信息,Java在java.lang.reflect 反射包下新增了AnnotatedElement接口,它主要用于表示目前正在 VM 中运行的程序中已使用注解的元素,通过该接口提供的方法可以利用反射技术地读取注解的信息,如反射包的Constructor类、Field类、Method类、Package类和Class类都实现了AnnotatedElement接口,它简要含义如下(更多详细介绍可以看 深入理解Java类型信息(Class对象)与反射机制):
Class:类的Class对象定义
Constructor:代表类的构造器定义
Field:代表类的成员变量定义
Method:代表类的方法定义
Package:代表类的包定义下面是AnnotatedElement中相关的API方法,以上5个类都实现以下的方法
返回值 方法名称 说明 <A extends Annotation>
getAnnotation(Class<A> annotationClass)
该元素如果存在指定类型的注解,则返回这些注解,否则返回 null。 Annotation[]
getAnnotations()
返回此元素上存在的所有注解,包括从父类继承的 boolean
isAnnotationPresent(Class<? extends Annotation> annotationClass)
如果指定类型的注解存在于此元素上,则返回 true,否则返回 false。 Annotation[]
getDeclaredAnnotations()
返回直接存在于此元素上的所有注解,注意,不包括父类的注解,调用者可以随意修改返回的数组;这不会对其他调用者返回的数组产生任何影响,没有则返回长度为0的数组 简单案例演示如下:
package com.zejian.annotationdemo; import java.lang.annotation.Annotation; import java.util.Arrays; /** * Created by zejian on 2017/5/20. * Blog : http://blog.csdn.net/javazejian [原文地址,请尊重原创] */ @DocumentA class A{ } //继承了A类 @DocumentB public class DocumentDemo extends A{ public static void main(String... args){ Class<?> clazz = DocumentDemo.class; //根据指定注解类型获取该注解 DocumentA documentA=clazz.getAnnotation(DocumentA.class); System.out.println("A:"+documentA); //获取该元素上的所有注解,包含从父类继承 Annotation[] an= clazz.getAnnotations(); System.out.println("an:"+ Arrays.toString(an)); //获取该元素上的所有注解,但不包含继承! Annotation[] an2=clazz.getDeclaredAnnotations(); System.out.println("an2:"+ Arrays.toString(an2)); //判断注解DocumentA是否在该元素上 boolean b=clazz.isAnnotationPresent(DocumentA.class); System.out.println("b:"+b); /** * 执行结果: A:@com.zejian.annotationdemo.DocumentA() an:[@com.zejian.annotationdemo.DocumentA(), @com.zejian.annotationdemo.DocumentB()] an2:@com.zejian.annotationdemo.DocumentB() b:true */ } }
运行时注解处理器
了解完注解与反射的相关API后,现在通过一个实例(该例子是博主改编自《Tinking in Java》)来演示利用运行时注解来组装数据库SQL的构建语句的过程
/** * Created by wuzejian on 2017/5/18. * 表注解 */ @Target(ElementType.TYPE)//只能应用于类上 @Retention(RetentionPolicy.RUNTIME)//保存到运行时 public @interface DBTable { String name() default ""; } /** * Created by wuzejian on 2017/5/18. * 注解Integer类型的字段 */ @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface SQLInteger { //该字段对应数据库表列名 String name() default ""; //嵌套注解 Constraints constraint() default @Constraints; } /** * Created by wuzejian on 2017/5/18. * 注解String类型的字段 */ @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface SQLString { //对应数据库表的列名 String name() default ""; //列类型分配的长度,如varchar(30)的30 int value() default 0; Constraints constraint() default @Constraints; } /** * Created by wuzejian on 2017/5/18. * 约束注解 */ @Target(ElementType.FIELD)//只能应用在字段上 @Retention(RetentionPolicy.RUNTIME) public @interface Constraints { //判断是否作为主键约束 boolean primaryKey() default false; //判断是否允许为null boolean allowNull() default false; //判断是否唯一 boolean unique() default false; } /** * Created by wuzejian on 2017/5/18. * 数据库表Member对应实例类bean */ @DBTable(name = "MEMBER") public class Member { //主键ID @SQLString(name = "ID",value = 50, constraint = @Constraints(primaryKey = true)) private String id; @SQLString(name = "NAME" , value = 30) private String name; @SQLInteger(name = "AGE") private int age; @SQLString(name = "DESCRIPTION" ,value = 150 , constraint = @Constraints(allowNull = true)) private String description;//个人描述 //省略set get..... }
上述定义4个注解,分别是@DBTable(用于类上)、@Constraints(用于字段上)、 @SQLString(用于字段上)、@SQLString(用于字段上)并在Member类中使用这些注解,这些注解的作用的是用于帮助注解处理器生成创建数据库表MEMBER的构建语句,在这里有点需要注意的是,我们使用了嵌套注解@Constraints,该注解主要用于判断字段是否为null或者字段是否唯一。必须清楚认识到上述提供的注解生命周期必须为
@Retention(RetentionPolicy.RUNTIME)
,即运行时,这样才可以使用反射机制获取其信息。有了上述注解和使用,剩余的就是编写上述的注解处理器了,前面我们聊了很多注解,其处理器要么是Java自身已提供、要么是框架已提供的,我们自己都没有涉及到注解处理器的编写,但上述定义处理SQL的注解,其处理器必须由我们自己编写了,如下package com.zejian.annotationdemo; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; /** * Created by zejian on 2017/5/13. * Blog : http://blog.csdn.net/javazejian [原文地址,请尊重原创] * 运行时注解处理器,构造表创建语句 */ public class TableCreator { public static String createTableSql(String className) throws ClassNotFoundException { Class<?> cl = Class.forName(className); DBTable dbTable = cl.getAnnotation(DBTable.class); //如果没有表注解,直接返回 if(dbTable == null) { System.out.println( "No DBTable annotations in class " + className); return null; } String tableName = dbTable.name(); // If the name is empty, use the Class name: if(tableName.length() < 1) tableName = cl.getName().toUpperCase(); List<String> columnDefs = new ArrayList<String>(); //通过Class类API获取到所有成员字段 for(Field field : cl.getDeclaredFields()) { String columnName = null; //获取字段上的注解 Annotation[] anns = field.getDeclaredAnnotations(); if(anns.length < 1) continue; // Not a db table column //判断注解类型 if(anns[0] instanceof SQLInteger) { SQLInteger sInt = (SQLInteger) anns[0]; //获取字段对应列名称,如果没有就是使用字段名称替代 if(sInt.name().length() < 1) columnName = field.getName().toUpperCase(); else columnName = sInt.name(); //构建语句 columnDefs.add(columnName + " INT" + getConstraints(sInt.constraint())); } //判断String类型 if(anns[0] instanceof SQLString) { SQLString sString = (SQLString) anns[0]; // Use field name if name not specified. if(sString.name().length() < 1) columnName = field.getName().toUpperCase(); else columnName = sString.name(); columnDefs.add(columnName + " VARCHAR(" + sString.value() + ")" + getConstraints(sString.constraint())); } } //数据库表构建语句 StringBuilder createCommand = new StringBuilder( "CREATE TABLE " + tableName + "("); for(String columnDef : columnDefs) createCommand.append("\n " + columnDef + ","); // Remove trailing comma String tableCreate = createCommand.substring( 0, createCommand.length() - 1) + ");"; return tableCreate; } /** * 判断该字段是否有其他约束 * @param con * @return */ private static String getConstraints(Constraints con) { String constraints = ""; if(!con.allowNull()) constraints += " NOT NULL"; if(con.primaryKey()) constraints += " PRIMARY KEY"; if(con.unique()) constraints += " UNIQUE"; return constraints; } public static void main(String[] args) throws Exception { String[] arg={"com.zejian.annotationdemo.Member"}; for(String className : arg) { System.out.println("Table Creation SQL for " + className + " is :\n" + createTableSql(className)); } /** * 输出结果: Table Creation SQL for com.zejian.annotationdemo.Member is : CREATE TABLE MEMBER( ID VARCHAR(50) NOT NULL PRIMARY KEY, NAME VARCHAR(30) NOT NULL, AGE INT NOT NULL, DESCRIPTION VARCHAR(150) ); */ } }
如果对反射比较熟悉的同学,上述代码就相对简单了,我们通过传递Member的全路径后通过Class.forName()方法获取到Member的class对象,然后利用Class对象中的方法获取所有成员字段Field,最后利用
field.getDeclaredAnnotations()
遍历每个Field上的注解再通过注解的类型判断来构建建表的SQL语句。这便是利用注解结合反射来构建SQL语句的简单的处理器模型,是否已回想起Hibernate?Java 8中注解增强
元注解@Repeatable
元注解@Repeatable是JDK1.8新加入的,它表示在同一个位置重复相同的注解。在没有该注解前,一般是无法在同一个类型上使用相同的注解的
//Java8前无法这样使用 @FilterPath("/web/update") @FilterPath("/web/add") public class A {}
Java8前如果是想实现类似的功能,我们需要在定义@FilterPath注解时定义一个数组元素接收多个值如下
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface FilterPath { String [] value(); } //使用 @FilterPath({"/update","/add"}) public class A { }
但在Java8新增了@Repeatable注解后就可以采用如下的方式定义并使用了
package com.zejian.annotationdemo; import java.lang.annotation.*; /** * Created by zejian on 2017/5/20. * Blog : http://blog.csdn.net/javazejian [原文地址,请尊重原创] */ //使用Java8新增@Repeatable原注解 @Target({ElementType.TYPE,ElementType.FIELD,ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Repeatable(FilterPaths.class)//参数指明接收的注解class public @interface FilterPath { String value(); } @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @interface FilterPaths { FilterPath[] value(); } //使用案例 @FilterPath("/web/update") @FilterPath("/web/add") @FilterPath("/web/delete") class AA{ }
我们可以简单理解为通过使用@Repeatable后,将使用@FilterPaths注解作为接收同一个类型上重复注解的容器,而每个@FilterPath则负责保存指定的路径串。为了处理上述的新增注解,Java8还在AnnotatedElement接口新增了getDeclaredAnnotationsByType() 和 getAnnotationsByType()两个方法并在接口给出了默认实现,在指定@Repeatable的注解时,可以通过这两个方法获取到注解相关信息。但请注意,旧版API中的getDeclaredAnnotation()和 getAnnotation()是不对@Repeatable注解的处理的(除非该注解没有在同一个声明上重复出现)。注意getDeclaredAnnotationsByType方法获取到的注解不包括父类,其实当 getAnnotationsByType()方法调用时,其内部先执行了getDeclaredAnnotationsByType方法,只有当前类不存在指定注解时,getAnnotationsByType()才会继续从其父类寻找,但请注意如果@FilterPath和@FilterPaths没有使用了@Inherited的话,仍然无法获取。下面通过代码来演示:
/** * Created by zejian on 2017/5/20. * Blog : http://blog.csdn.net/javazejian [原文地址,请尊重原创] */ //使用Java8新增@Repeatable原注解 @Target({ElementType.TYPE,ElementType.FIELD,ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Repeatable(FilterPaths.class) public @interface FilterPath { String value(); } @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @interface FilterPaths { FilterPath[] value(); } @FilterPath("/web/list") class CC { } //使用案例 @FilterPath("/web/update") @FilterPath("/web/add") @FilterPath("/web/delete") class AA extends CC{ public static void main(String[] args) { Class<?> clazz = AA.class; //通过getAnnotationsByType方法获取所有重复注解 FilterPath[] annotationsByType = clazz.getAnnotationsByType(FilterPath.class); FilterPath[] annotationsByType2 = clazz.getDeclaredAnnotationsByType(FilterPath.class); if (annotationsByType != null) { for (FilterPath filter : annotationsByType) { System.out.println("1:"+filter.value()); } } System.out.println("-----------------"); if (annotationsByType2 != null) { for (FilterPath filter : annotationsByType2) { System.out.println("2:"+filter.value()); } } System.out.println("使用getAnnotation的结果:"+clazz.getAnnotation(FilterPath.class)); /** * 执行结果(当前类拥有该注解FilterPath,则不会从CC父类寻找) 1:/web/update 1:/web/add 1:/web/delete ----------------- 2:/web/update 2:/web/add 2:/web/delete 使用getAnnotation的结果:null */ } }
从执行结果来看如果当前类拥有该注解@FilterPath,则getAnnotationsByType方法不会从CC父类寻找,下面看看另外一种情况,即AA类上没有@FilterPath注解
/** * Created by zejian on 2017/5/20. * Blog : http://blog.csdn.net/javazejian [原文地址,请尊重原创] */ //使用Java8新增@Repeatable原注解 @Target({ElementType.TYPE,ElementType.FIELD,ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Inherited //添加可继承元注解 @Repeatable(FilterPaths.class) public @interface FilterPath { String value(); } @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Inherited //添加可继承元注解 @interface FilterPaths { FilterPath[] value(); } @FilterPath("/web/list") @FilterPath("/web/getList") class CC { } //AA上不使用@FilterPath注解,getAnnotationsByType将会从父类查询 class AA extends CC{ public static void main(String[] args) { Class<?> clazz = AA.class; //通过getAnnotationsByType方法获取所有重复注解 FilterPath[] annotationsByType = clazz.getAnnotationsByType(FilterPath.class); FilterPath[] annotationsByType2 = clazz.getDeclaredAnnotationsByType(FilterPath.class); if (annotationsByType != null) { for (FilterPath filter : annotationsByType) { System.out.println("1:"+filter.value()); } } System.out.println("-----------------"); if (annotationsByType2 != null) { for (FilterPath filter : annotationsByType2) { System.out.println("2:"+filter.value()); } } System.out.println("使用getAnnotation的结果:"+clazz.getAnnotation(FilterPath.class)); /** * 执行结果(当前类没有@FilterPath,getAnnotationsByType方法从CC父类寻找) 1:/web/list 1:/web/getList ----------------- 使用getAnnotation的结果:null */ } }
注意定义@FilterPath和@FilterPath时必须指明@Inherited,getAnnotationsByType方法否则依旧无法从父类获取@FilterPath注解,这是为什么呢,不妨看看getAnnotationsByType方法的实现源码:
//接口默认实现方法 default <T extends Annotation> T[] getAnnotationsByType(Class<T> annotationClass) { //先调用getDeclaredAnnotationsByType方法 T[] result = getDeclaredAnnotationsByType(annotationClass); //判断当前类获取到的注解数组是否为0 if (result.length == 0 && this instanceof Class && //判断定义注解上是否使用了@Inherited元注解 AnnotationType.getInstance(annotationClass).isInherited()) { // Inheritable //从父类获取 Class<?> superClass = ((Class<?>) this).getSuperclass(); if (superClass != null) { result = superClass.getAnnotationsByType(annotationClass); } } return result; }
新增的两种ElementType
在Java8中 ElementType 新增两个枚举成员,TYPE_PARAMETER 和 TYPE_USE ,在Java8前注解只能标注在一个声明(如字段、类、方法)上,Java8后,新增的TYPE_PARAMETER可以用于标注类型参数,而TYPE_USE则可以用于标注任意类型(不包括class)。如下所示
//TYPE_PARAMETER 标注在类型参数上 class D<@Parameter T> { } //TYPE_USE则可以用于标注任意类型(不包括class) //用于父类或者接口 class Image implements @Rectangular Shape { } //用于构造函数 new @Path String("/usr/bin") //用于强制转换和instanceof检查,注意这些注解中用于外部工具,它们不会对类型转换或者instanceof的检查行为带来任何影响。 String path=(@Path String)input; if(input instanceof @Path String) //用于指定异常 public Person read() throws @Localized IOException. //用于通配符绑定 List<@ReadOnly ? extends Person> List<? extends @ReadOnly Person> @NotNull String.class //非法,不能标注class import java.lang.@NotNull String //非法,不能标注import
这里主要说明一下TYPE_USE,类型注解用来支持在Java的程序中做强类型检查,配合第三方插件工具(如Checker Framework),可以在编译期检测出runtime error(如UnsupportedOperationException、NullPointerException异常),避免异常延续到运行期才发现,从而提高代码质量,这就是类型注解的主要作用。总之Java 8 新增加了两个注解的元素类型ElementType.TYPE_USE 和ElementType.TYPE_PARAMETER ,通过它们,我们可以把注解应用到各种新场合中。
ok~,关于注解暂且聊到这,实际上还有一个大块的知识点没详细聊到,源码级注解处理器,这个话题博主打算后面另开一篇分析。
主要参考资料 《Thinking in Java》
如果您喜欢我写的博文,读后觉得收获很大,不妨小额赞助我一下,让我有动力继续写出高质量的博文,感谢您的赞赏!支付宝、微信
-
Java注解annotation invalid type of annotation member
2019-11-05 11:07:07文章目录Java注解annotation : invalid type of annotation member1、什么是invalid type of annotation member2、哪些类型是合法的3、对应说明 Java注解annotation : invalid type of annotation member 1、什么是... -
Annotation-自定义Annotation
2016-10-17 17:26:29定义Annotation定义Annotation使用@interface关键字,定义的Annotation可带有成员变量,定义的成员变量,在Annotation中以无形参的方法形式来声明。public @interface Person { String name(); int age(); }public ... -
-
Annotation--自定义Annotation
2017-09-11 21:25:44掌握自定义Annotation的简单格式 可以使用Annotation接受设置的内容 可以为Annotation重的变量指定默认值 可以使用枚举指定Annotation的取值范围 掌握Retention以及RetentionPolicy的作用 二,具体内容 ... -
Annotation详解
2017-03-26 02:05:17Annotation 前言:作为一名Android开发人员,在使用Java开发代码的时候不免会经常看到一些注解信息,或者是在使用一些三方的开源框架的代码时候看到一些别人的自定义注解,比如Retrofit,Butter Knife,... -
idea关于找不到包的问题,比如:Java:程序包org.springframework.beans.factory.annotation不存在
2017-12-22 11:43:37打开我自己建的temp文件夹,存的...idea关于找不到包的问题,比如:Java:程序包org.springframework.beans.factory.annotation不存在,像这样子 肿么办? 1、打开http://mvnrepository.com/search?q=org.apach
-
maven-3.6.0已配好国内镜像地址
-
python办公自动化技巧
-
windows下的socket tcp压力测试工具(附突破连接限制的方法和工具).zip
-
360360安全卫士.e
-
系统盘.iso 中小学材料系统的系统盘,绿色的
-
windows xp3 sam
-
易语言开发通达信DLL公式接口
-
备战2021软考网络规划设计师历年真题套餐
-
QT 简单计算器
-
【数据分析-随到随学】Tableau数据分 析+PowerBI
-
web前端开发规范
-
【Leetcode】974. Subarray Sums Divisible by K
-
浙江、江苏移动数码SM代工M301H 不拆机room
-
阿里云云计算ACP考试必备教程
-
队列(c语言)
-
(新)备战2021软考网络规划设计师培训学习套餐
-
【Dubbo】配置详解 --标签、配置项、使用建议
-
【2021】UI自动化测试框架(Selenium3)
-
第12章 图像轮廓 -- 查找图像轮廓 cv2.findContours()
-
install_flash_player_ax_cn_34_0_0_92离线安装包