欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

浅谈Java自定义注解和运行时靠反射获取注解

程序员文章站 2024-03-09 16:26:59
java自定义注解 java注解是附加在代码中的一些元信息,用于一些工具在编译、运行时进行解析和使用,起到说明、配置的功能。 注解不会也不能影响代码的实际逻辑,仅仅起到...

java自定义注解

java注解是附加在代码中的一些元信息,用于一些工具在编译、运行时进行解析和使用,起到说明、配置的功能。

注解不会也不能影响代码的实际逻辑,仅仅起到辅助性的作用。包含在 java.lang.annotation 包中。

1、元注解

元注解是指注解的注解。包括  @retention @target @document @inherited四种。

1.1、@retention: 定义注解的保留策略

@retention(retentionpolicy.source)  //注解仅存在于源码中,在class字节码文件中不包含
@retention(retentionpolicy.class)   // 默认的保留策略,注解会在class字节码文件中存在,但运行时无法获得,
@retention(retentionpolicy.runtime) // 注解会在class字节码文件中存在,在运行时可以通过反射获取到

注解类:

@retention(retentionpolicy.runtime) // 注解会在class字节码文件中存在,在运行时可以通过反射获取到
@target({elementtype.field,elementtype.method})//定义注解的作用目标**作用范围字段、枚举的常量/方法
@documented//说明该注解将被包含在javadoc中
public @interface fieldmeta {

	/**
	 * 是否为序列号
	 * @return
	 */
	boolean id() default false;
	/**
	 * 字段名称
	 * @return
	 */
	string name() default "";
	/**
	 * 是否可编辑
	 * @return
	 */
	boolean editable() default true;
	/**
	 * 是否在列表中显示
	 * @return
	 */
	boolean summary() default true;
	/**
	 * 字段描述
	 * @return
	 */
	string description() default "";
	/**
	 * 排序字段
	 * @return
	 */
	int order() default 0;
}

实体类:

public class anno {

	@fieldmeta(id=true,name="序列号",order=1)
	private int id;
	@fieldmeta(name="姓名",order=3)
	private string name;
	@fieldmeta(name="年龄",order=2)
	private int age;
	
	@fieldmeta(description="描述",order=4)
	public string desc(){
		return "java反射获取annotation的测试";
	}
	
	public int getid() {
		return id;
	}
	public void setid(int id) {
		this.id = id;
	}
	public string getname() {
		return name;
	}
	public void setname(string name) {
		this.name = name;
	}
	public int getage() {
		return age;
	}
	public void setage(int age) {
		this.age = age;
	}
	
}

获取到注解的帮助类:

public class sortablefield {

	public sortablefield(){}
	
	public sortablefield(fieldmeta meta, field field) {
		super();
		this.meta = meta;
		this.field = field;
		this.name=field.getname();
		this.type=field.gettype();
	}
	
	
	public sortablefield(fieldmeta meta, string name, class<?> type) {
		super();
		this.meta = meta;
		this.name = name;
		this.type = type;
	}


	private fieldmeta meta;
	private field field;
	private string name;
	private class<?> type;
	
	public fieldmeta getmeta() {
		return meta;
	}
	public void setmeta(fieldmeta meta) {
		this.meta = meta;
	}
	public field getfield() {
		return field;
	}
	public void setfield(field field) {
		this.field = field;
	}
	public string getname() {
		return name;
	}
	public void setname(string name) {
		this.name = name;
	}

	public class<?> gettype() {
		return type;
	}

	public void settype(class<?> type) {
		this.type = type;
	}
	
	
}

运行时获取注解,首先创建一个基类:

public class parent<t> {

	private class<t> entity;

	public parent() {
		init();
	}

	@suppresswarnings("unchecked")
	public list<sortablefield> init(){
		list<sortablefield> list = new arraylist<sortablefield>();
		/**getclass().getgenericsuperclass()返回表示此 class 所表示的实体(类、接口、基本类型或 void)
		 * 的直接超类的 type(class<t>泛型中的类型),然后将其转换parameterizedtype。。
		 * 	getactualtypearguments()返回表示此类型实际类型参数的 type 对象的数组。
		 * 	[0]就是这个数组中第一个了。。
		 * 	简而言之就是获得超类的泛型参数的实际类型。。*/
		entity = (class<t>)((parameterizedtype)this.getclass().getgenericsuperclass())
				.getactualtypearguments()[0];
//		fieldmeta filed = entity.getannotation(fieldmeta.class);
		
		if(this.entity!=null){
			
			/**返回类中所有字段,包括公共、保护、默认(包)访问和私有字段,但不包括继承的字段
			 * entity.getfields();只返回对象所表示的类或接口的所有可访问公共字段
			 * 在class中getdeclared**()方法返回的都是所有访问权限的字段、方法等;
			 * 可看api
			 * */
			field[] fields = entity.getdeclaredfields();
//			
			for(field f : fields){
				//获取字段中包含fieldmeta的注解
				fieldmeta meta = f.getannotation(fieldmeta.class);
				if(meta!=null){
					sortablefield sf = new sortablefield(meta, f);
					list.add(sf);
				}
			}
			
			//返回对象所表示的类或接口的所有可访问公共方法
			method[] methods = entity.getmethods();
			
			for(method m:methods){
				fieldmeta meta = m.getannotation(fieldmeta.class);
				if(meta!=null){
					sortablefield sf = new sortablefield(meta,m.getname(),m.getreturntype());
					list.add(sf);
				}
			}
			//这种方法是新建fieldsortcom类实现comparator接口,来重写compare方法实现排序
//			collections.sort(list, new fieldsortcom());
			collections.sort(list, new comparator<sortablefield>() {
				@override
				public int compare(sortablefield s1,sortablefield s2) {
					return s1.getmeta().order()-s2.getmeta().order();
//					return s1.getname().compareto(s2.getname());//也可以用compare来比较
				}
				
			});
		}
		return list;
		
	}
}

创建子类继承基类:

public class child extends parent<anno>{

}

测试类:

public class testannotation {

	@suppresswarnings({ "unchecked", "rawtypes" })
	public static void main(string[] args) {
		parent c = new child();
		list<sortablefield> list = c.init();//获取泛型中类里面的注解
		//输出结果
		for(sortablefield l : list){
			system.out.println("字段名称:"+l.getname()+"\t字段类型:"+l.gettype()+
					"\t注解名称:"+l.getmeta().name()+"\t注解描述:"+l.getmeta().description());
		}
	}
}

////////////////////////////////////////////////////////////////////////////////////////////////////////

1、annotation的工作原理:

jdk5.0中提供了注解的功能,允许开发者定义和使用自己的注解类型。该功能由一个定义注解类型的语法和描述一个注解声明的语法,读取注解的api,一个使用注解修饰的class文件和一个注解处理工具组成。

annotation并不直接影响代码的语义,但是他可以被看做是程序的工具或者类库。它会反过来对正在运行的程序语义有所影响。

annotation可以冲源文件、class文件或者在运行时通过反射机制多种方式被读取。

2、@override注解:

java.lang

注释类型 override
@target(value=method)
@retention(value=source)
public @interface override表示一个方法声明打算重写超类中的另一个方法声明。如果方法利用此注释类型进行注解但没有重写超类方法,则编译器会生成一条错误消息。

@override注解表示子类要重写父类的对应方法。

override是一个marker annotation,用于标识的annotation,annotation名称本身表示了要给工具程序的信息。

下面是一个使用@override注解的例子:

class a {
  private string id;
  a(string id){
    this.id = id;
  }
  @override
  public string tostring() {
    return id;
  }
}

3、@deprecated注解:

java.lang
注释类型 deprecated
@documented
@retention(value=runtime)

public @interface deprecated用 @deprecated 注释的程序元素,不鼓励程序员使用这样的元素,通常是因为它很危险或存在更好的选择。在使用不被赞成的程序元素或在不被赞成的代码中执行重写时,编译器会发出警告。

@deprecated注解表示方法是不被建议使用的。

deprecated是一个marker annotation。

下面是一个使用@deprecated注解的例子:

class a {
  private string id;
  a(string id){
    this.id = id;
  }
  @deprecated
  public void execute(){
    system.out.println(id);
  }
  public static void main(string[] args) {
    a a = new a("a123");
    a.execute();
  }
}

4、@suppresswarnings注解:

java.lang
注释类型 suppresswarnings
@target(value={type,field,method,parameter,constructor,local_variable})
@retention(value=source)

public @interface suppresswarnings指示应该在注释元素(以及包含在该注释元素中的所有程序元素)中取消显示指定的编译器警告。注意,在给定元素中取消显示的警告集是所有包含元素中取消显示的警告的超集。例如,如果注释一个类来取消显示某个警告,同时注释一个方法来取消显示另一个警告,那么将在此方法中同时取消显示这两个警告。

根据风格不同,程序员应该始终在最里层的嵌套元素上使用此注释,在那里使用才有效。如果要在特定的方法中取消显示某个警告,则应该注释该方法而不是注释它的类。

@suppresswarnings注解表示抑制警告。

下面是一个使用@suppresswarnings注解的例子:

@suppresswarnings("unchecked")
public static void main(string[] args) {
  list list = new arraylist();
  list.add("abc");
}

5、自定义注解:

使用@interface自定义注解时,自动继承了java.lang.annotation.annotation接口,由编译程序自动完成其他细节。在定义注解时,不能继承其他的注解或接口。

自定义最简单的注解:

public @interface myannotation {

}

使用自定义注解:

public class annotationtest2 {

  @myannotation
  public void execute(){
    system.out.println("method");
  }
}

5.1、添加变量:

public @interface myannotation {

  string value1();
}

使用自定义注解:

public class annotationtest2 {

  @myannotation(value1="abc")
  public void execute(){
    system.out.println("method");
  }
}

当注解中使用的属性名为value时,对其赋值时可以不指定属性的名称而直接写上属性值接口;除了value意外的变量名都需要使用name=value的方式赋值。

5.2、添加默认值:

public @interface myannotation {

  string value1() default "abc";
}

5.3、多变量使用枚举:

public @interface myannotation {

  string value1() default "abc";
  myenum value2() default myenum.sunny;
}
enum myenum{
  sunny,rainy
}

使用自定义注解:

public class annotationtest2 {

  @myannotation(value1="a", value2=myenum.sunny)
  public void execute(){
    system.out.println("method");
  }
}

5.4、数组变量:

public @interface myannotation {

  string[] value1() default "abc";
}

使用自定义注解:

public class annotationtest2 {

  @myannotation(value1={"a","b"})
  public void execute(){
    system.out.println("method");
  }
}

6、设置注解的作用范围:

@documented
@retention(value=runtime)
@target(value=annotation_type)

public @interface retention指示注释类型的注释要保留多久。如果注释类型声明中不存在 retention 注释,则保留策略默认为 retentionpolicy.class。

只有元注释类型直接用于注释时,target 元注释才有效。如果元注释类型用作另一种注释类型的成员,则无效。

public enum retentionpolicy
extends enum<retentionpolicy>注释保留策略。此枚举类型的常量描述保留注释的不同策略。它们与 retention 元注释类型一起使用,以指定保留多长的注释。

class
编译器将把注释记录在类文件中,但在运行时 vm 不需要保留注释。

runtime
编译器将把注释记录在类文件中,在运行时 vm 将保留注释,因此可以反射性地读取。

source
编译器要丢弃的注释。@retention注解可以在定义注解时为编译程序提供注解的保留策略。

属于class保留策略的注解有@suppresswarnings,该注解信息不会存储于.class文件。

6.1、在自定义注解中的使用例子:

@retention(retentionpolicy.class)
public @interface myannotation {

  string[] value1() default "abc";
}

7、使用反射读取runtime保留策略的annotation信息的例子:

java.lang.reflect

接口 annotatedelement

所有已知实现类:

accessibleobject, class, constructor, field, method, package表示目前正在此 vm 中运行的程序的一个已注释元素。该接口允许反射性地读取注释。由此接口中的方法返回的所有注释都是不可变并且可序列化的。调用者可以修改已赋值数组枚举成员的访问器返回的数组;这不会对其他调用者返回的数组产生任何影响。

如果此接口中的方法返回的注释(直接或间接地)包含一个已赋值的 class 成员,该成员引用了一个在此 vm 中不可访问的类,则试图通过在返回的注释上调用相关的类返回的方法来读取该类,将导致一个 typenotpresentexception。

isannotationpresent
boolean isannotationpresent(class<? extends annotation> annotationclass)如果指定类型的注释存在于此元素上,则返回 true,否则返回 false。此方法主要是为了便于访问标记注释而设计的。

参数:

annotationclass - 对应于注释类型的 class 对象

返回:

如果指定注释类型的注释存在于此对象上,则返回 true,否则返回 false

抛出:

nullpointerexception - 如果给定的注释类为 null

从以下版本开始:

1.5

getannotation
<t extends annotation> t getannotation(class<t> annotationclass)如果存在该元素的指定类型的注释,则返回这些注释,否则返回 null。

参数:

annotationclass - 对应于注释类型的 class 对象

返回:

如果该元素的指定注释类型的注释存在于此对象上,则返回这些注释,否则返回 null

抛出:

nullpointerexception - 如果给定的注释类为 null

从以下版本开始:

1.5

getannotations
annotation[] getannotations()返回此元素上存在的所有注释。(如果此元素没有注释,则返回长度为零的数组。)该方法的调用者可以随意修改返回的数组;这不会对其他调用者返回的数组产生任何影响。

返回:

此元素上存在的所有注释

从以下版本开始:

1.5

getdeclaredannotations
annotation[] getdeclaredannotations()返回直接存在于此元素上的所有注释。与此接口中的其他方法不同,该方法将忽略继承的注释。(如果没有注释直接存在于此元素上,则返回长度为零的一个数组。)该方法的调用者可以随意修改返回的数组;这不会对其他调用者返回的数组产生任何影响。

返回:

直接存在于此元素上的所有注释

从以下版本开始:

1.5

下面是使用反射读取runtime保留策略的annotation信息的例子:

自定义注解:

@retention(retentionpolicy.runtime)
public @interface myannotation {

  string[] value1() default "abc";
}

使用自定义注解:

public class annotationtest2 {

  @myannotation(value1={"a","b"})
  @deprecated
  public void execute(){
    system.out.println("method");
  }
}

读取注解中的信息:

public static void main(string[] args) throws securityexception, nosuchmethodexception, illegalargumentexception, illegalaccessexception, invocationtargetexception {
  annotationtest2 annotationtest2 = new annotationtest2();
  //获取annotationtest2的class实例
  class<annotationtest2> c = annotationtest2.class;
  //获取需要处理的方法method实例
  method method = c.getmethod("execute", new class[]{});
  //判断该方法是否包含myannotation注解
  if(method.isannotationpresent(myannotation.class)){
    //获取该方法的myannotation注解实例
    myannotation myannotation = method.getannotation(myannotation.class);
    //执行该方法
    method.invoke(annotationtest2, new object[]{});
    //获取myannotation
    string[] value1 = myannotation.value1();
    system.out.println(value1[0]);
  }
  //获取方法上的所有注解
  annotation[] annotations = method.getannotations();
  for(annotation annotation : annotations){
    system.out.println(annotation);
  }
}

8、限定注解的使用:

限定注解使用@target。

@documented
@retention(value=runtime)
@target(value=annotation_type)

public @interface target指示注释类型所适用的程序元素的种类。如果注释类型声明中不存在 target 元注释,则声明的类型可以用在任一程序元素上。如果存在这样的元注释,则编译器强制实施指定的使用限制。 例如,此元注释指示该声明类型是其自身,即元注释类型。它只能用在注释类型声明上:

@target(elementtype.annotation_type)
  public @interface metaannotationtype {
    ...
  }

此元注释指示该声明类型只可作为复杂注释类型声明中的成员类型使用。它不能直接用于注释:

@target({}) 
  public @interface membertype {
    ...
  }

这是一个编译时错误,它表明一个 elementtype 常量在 target 注释中出现了不只一次。例如,以下元注释是非法的:

@target({elementtype.field, elementtype.method, elementtype.field})
  public @interface bogus {
    ...
  }public enum elementtype

extends enum<elementtype>程序元素类型。此枚举类型的常量提供了 java 程序中声明的元素的简单分类。

这些常量与 target 元注释类型一起使用,以指定在什么情况下使用注释类型是合法的。

annotation_type
注释类型声明
constructor
构造方法声明
field
字段声明(包括枚举常量)
local_variable
局部变量声明
method
方法声明
package
包声明
parameter
参数声明
type
类、接口(包括注释类型)或枚举声明

注解的使用限定的例子:

@target(elementtype.method)
public @interface myannotation {

  string[] value1() default "abc";
}

9、在帮助文档中加入注解:

要想在制作javadoc文件的同时将注解信息加入到api文件中,可以使用java.lang.annotation.documented。

在自定义注解中声明构建注解文档:

@documented
public @interface myannotation {

  string[] value1() default "abc";
}

使用自定义注解:

public class annotationtest2 {

  @myannotation(value1={"a","b"})
  public void execute(){
    system.out.println("method");
  }
}

10、在注解中使用继承:

默认情况下注解并不会被继承到子类中,可以在自定义注解时加上java.lang.annotation.inherited注解声明使用继承。

@documented
@retention(value=runtime)
@target(value=annotation_type)
public @interface inherited指示注释类型被自动继承。如果在注释类型声明中存在 inherited 元注释,并且用户在某一类声明中查询该注释类型,同时该类声明中没有此类型的注释,则将在该类的超类中自动查询该注释类型。此过程会重复进行,直到找到此类型的注释或到达了该类层次结构的顶层 (object) 为止。如果没有超类具有该类型的注释,则查询将指示当前类没有这样的注释。

注意,如果使用注释类型注释类以外的任何事物,此元注释类型都是无效的。还要注意,此元注释仅促成从超类继承注释;对已实现接口的注释无效。

以上这篇浅谈java自定义注解和运行时靠反射获取注解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。