版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
注解
## 注解的创建
· 1. 在一个包中新建一个Annotation;
· 2. 创建Annotation时需要填写三个必要点:Name、@Retention、@Target
·
·@Retention的含义是源注解,Source是指保存在源码级别,Class是指保存到class文件,Runtime不仅会在class文件中保存,JVM加载完class文件依然存在;
·@Target是指所修饰的对象范围,常用type类型,field成员,method方法等;
注解的应用
## 几个基本注解以及一个用了注解的类
其中ClassName和ClassTable是用在类型上的,Type是应用在Field上面,Point是一个应用了两种注解的类,给出Point类中注解的使用。
package com.vae.annotation.core;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
@Retention(RUNTIME)
@Target(FIELD)
public @interface Type {
String value();
}
在Point中的使用如下,格式为@注解名(属性名 = 值)(如果没有属性可以只有注解名),如果注解中的属性以value命名,则在使用中可以直接在括号中写值,如若不是要写(属性名 = 值),但如果有两个及两个以上不可以直接赋值,必须写清楚是给哪一个属性赋值:
对于应用了注解的类或成员可以有很多功能来处理,如检测该类是不是注解,取出该类中所有的注解以及注解名,以及属性的值。
package com.vae.annotation.test;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import com.vae.annotation.core.ClassName;
import com.vae.annotation.core.Type;
public class Test {
public static void main(String[] args) {
try {
Class<?> klass = Class.forName("com.vae.annotation.core.Point");
System.out.println("检测该类是否是一个注解: " + klass.isAnnotation());
System.out.println("检测该类是否包含ClassName注解: " + klass.isAnnotationPresent(ClassName.class));
System.out.println("检测该类是否包含Type注解: " + klass.isAnnotationPresent(Type.class));
//得到加到该类上面的所有注解并形成数组
Annotation[] annotations = klass.getAnnotations();
for (Annotation annotation : annotations) {
System.out.println("该注解是 " + annotation + " 注解");
}
ClassName className = klass.getAnnotation(ClassName.class);
System.out.println("该注解的名字是: " + className);
//得到该类的所有成员并形成数组,遍历该数组,一一获取每个成员上加的注解并作出相关操作
//klass.getDeclaredFields()是可以取出包括private权限的所有成员
Field[] fields = klass.getDeclaredFields();
for (Field field : fields) {
Type type = field.getAnnotation(Type.class);
System.out.println("取出该类中Type.class注解的值" + type.value());
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
运行结果如下:
关于注解的一些适用场合
在一些情况下可以替换xml文件结合反射机制,省去配置文件的编写,并且在反射机制中反射得到的方法参数均为arg0,arg1等不清晰的名字,进行赋值时若有类型相同的参数无法区分,但用注解可以分别将各个参数的名字用属性的值来写出,并别获取,就可以区分同类型参数来进行赋值。并且注解也可以与包扫描等一些工具结合使用。在Spring框架中也会用到注解。