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

java语言注解基础概念详解

程序员文章站 2023-12-21 13:36:34
1、retentionpolicy.source:注解只保留在源文件,当java文件编译成class文件的时候,注解被遗弃; 2、retentionpolicy.clas...

1、retentionpolicy.source:注解只保留在源文件,当java文件编译成class文件的时候,注解被遗弃;

2、retentionpolicy.class:注解被保留到class文件,但jvm加载class文件时候被遗弃,这是默认的生命周期;

3、retentionpolicy.runtime:注解不仅被保存到class文件中,jvm加载class文件之后,仍然存在;

这3个生命周期分别对应于:java源文件(.java文件)--->.class文件--->内存中的字节码。

那怎么来选择合适的注解生命周期呢?

首先要明确生命周期长度source<class<runtime,所以前者能作用的地方后者一定也能作用。一般如果需要在运行时去动态获取注解信息,那只能用runtime注解;如果要在编译时进行一些预处理操作,比如生成一些辅助代码(如butterknife),就用class注解;如果只是做一些检查性的操作,比如@override和@suppresswarnings,则可选用source注解。

下面来介绍下运行时注解的简单运用。

获取注解

你需要通过反射来获取运行时注解,可以从package、class、field、method...上面获取,基本方法都一样,几个常见的方法如下:

/** 
 * 获取指定类型的注解 
 */
public <a extends annotation> a getannotation(class<a> annotationtype);
/** 
 * 获取所有注解,如果有的话 
 */
public annotation[] getannotations();
/** 
 * 获取所有注解,忽略继承的注解 
 */
public annotation[] getdeclaredannotations();
/** 
 * 指定注解是否存在该元素上,如果有则返回true,否则false 
 */
public boolean isannotationpresent(class<? extends annotation> annotationtype);
/** 
 * 获取method中参数的所有注解 
 */
public annotation[][] getparameterannotations();

要使用这些函数必须先通过反射获取到对应的元素:class、field、method等。

自定义注解

来看下自定义注解的简单使用方式,这里先定义3个运行时注解:

// 适用类、接口(包括注解类型)或枚举 
@retention(retentionpolicy.runtime) 
@target(elementtype.type) 
public @interface classinfo { 
  string value(); 
} 
// 适用field属性,也包括enum常量 
@retention(retentionpolicy.runtime) 
@target(elementtype.field) 
public @interface fieldinfo { 
  int[] value(); 
} 
// 适用方法 
@retention(retentionpolicy.runtime) 
@target(elementtype.method) 
public @interface methodinfo { 
  string name() default "long"; 
  string data(); 
  int age() default 27; 
} 

这3个注解分别适用于不同的元素,并都带有不同的属性,在使用注解是需要设置这些属性值。

再定义一个测试类来使用这些注解:

/** 
 * 测试运行时注解 
 */
@classinfo("test class") 
public class testruntimeannotation {
	@fieldinfo(value = {1, 2}) 
	  public string fieldinfo = "filedinfo";
	@fieldinfo(value = {10086}) 
	  public int i = 100;
	@methodinfo(name = "bluebird", data = "big") 
	  public static string getmethodinfo() {
		return testruntimeannotation.class.getsimplename();
	}
}

使用还是很简单的,最后来看怎么在代码中获取注解信息:

/** 
 * 测试运行时注解 
 */
private void _testruntimeannotation() {
	stringbuffer sb = new stringbuffer();
	class<?> cls = testruntimeannotation.class;
	constructor<?>[] constructors = cls.getconstructors();
	// 获取指定类型的注解 
	sb.append("class注解:").append("\n");
	classinfo classinfo = cls.getannotation(classinfo.class);
	if (classinfo != null) {
		sb.append(modifier.tostring(cls.getmodifiers())).append(" ") 
		        .append(cls.getsimplename()).append("\n");
		sb.append("注解值: ").append(classinfo.value()).append("\n\n");
	}
	sb.append("field注解:").append("\n");
	field[] fields = cls.getdeclaredfields();
	for (field field : fields) {
		fieldinfo fieldinfo = field.getannotation(fieldinfo.class);
		if (fieldinfo != null) {
			sb.append(modifier.tostring(field.getmodifiers())).append(" ") 
			          .append(field.gettype().getsimplename()).append(" ") 
			          .append(field.getname()).append("\n");
			sb.append("注解值: ").append(arrays.tostring(fieldinfo.value())).append("\n\n");
		}
	}
	sb.append("method注解:").append("\n");
	method[] methods = cls.getdeclaredmethods();
	for (method method : methods) {
		methodinfo methodinfo = method.getannotation(methodinfo.class);
		if (methodinfo != null) {
			sb.append(modifier.tostring(method.getmodifiers())).append(" ") 
			          .append(method.getreturntype().getsimplename()).append(" ") 
			          .append(method.getname()).append("\n");
			sb.append("注解值: ").append("\n");
			sb.append("name: ").append(methodinfo.name()).append("\n");
			sb.append("data: ").append(methodinfo.data()).append("\n");
			sb.append("age: ").append(methodinfo.age()).append("\n");
		}
	}
	system.out.print(sb.tostring());
}

所做的操作都是通过反射获取对应元素,再获取元素上面的注解,最后得到注解的属性值。

看一下输出情况,这里我直接显示在手机上:

java语言注解基础概念详解

总结

以上就是本文关于java语言注解基础概念详解的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

上一篇:

下一篇: