java元注解
最近由于项目需要,要使得项目的扩展性更好,想借用自定义的注解来解决静态工厂的不足,故研究了一下java中注解的用法。
我们最常见的java中的注解要数@Override了,这个注解的意思代表,此方法是重写的方法。除了此注解,java中的注解还有很多很多。尤其是我们使用spring和spring mvc的时候,很多不同含义的注解使得我们的代码看起来简洁了很多。java中的注解主要在java.lang.annotation包中实现。
今天先简单介绍一下java中的元注解,元注解,由名字可知他们是注解的一些属性、一些描述。我们在自定义注解的时候,需要这些元注解来给我们自定义的注解赋予一些属性。
java中的元注解主要包含4个,分别是@Documented、@Inherited、@Retention、@Target,下面将分别介绍各自的含义及用法:
1.@Documented
@Documented用于描述其它类型的annotation应该被作为被标注的程序成员的公共API,因此可以被例如javadoc此类的工具文档化。Documented是一个标记注解,没有成员。
2.@Inherited
@Inherited 元注解是一个标记注解,@Inherited阐述了某个被标注的类型是被继承的。如果一个使用了@Inherited修饰的annotation类型被用于一个class,则这个annotation将被用于该class的子类。
3.@Retention
@Target说明了Annotation所修饰的对象范围:Annotation可被用于 packages、types(类、接口、枚举、Annotation类型)、类型成员(方法、构造方法、成员变量、枚举值)、方法参数和本地变量(如循环变量、catch参数)。
ElementType.CONSTRUCTOR 作用于构造器
ElementType.FIELD 作用于域/属性
ElementType.LOCAL_VARIABLE 作用于描述局部变量
ElementType.METHOD 作用于方法
ElementType.PACKAGE 作用于描述包
ElementType.PARAMETER 作用于描述参数
ElementType.TYPE 作用于描述类、接口(包括注解类型) 或enum声明,最常用
用法示例:
//单个修饰对象的范围:
@Target(ElementType.TYPE)
//多个修饰对象的范围:
@Target({ ElementType.TYPE, ElementType.METHOD})
4.@Target
定义了该Annotation被保留的时间长短:某些Annotation仅出现在源代码中,而被编译器丢弃;而另一些却被编译在class文件中;编译在class文件中的Annotation可能会被虚拟机忽略,而另一些在class被装载时将被读取(请注意并不影响class的执行,因为Annotation与class在使用上是被分离的)。使用这个meta-Annotation可以对 Annotation的“生命周期”限制。
RetentionPolicy.RUNTIME 注解会在class字节码文件中存在,在运行时可以通过反射获取到
RetentionPolicy.CLASS 默认的保留策略,注解会在class字节码文件中存在,但运行时无法获得
RetentionPolicy.SOURCE 注解仅存在于源码中,在class字节码文件中不包含
example:
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
*
* @author qxl
* @date 2016年11月23日 下午12:57:53
* @version 1.0.0
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface Person {
String name();
int age();
}
/**
*
* @author qxl
* @date 2016年11月23日 下午3:48:38
* @version 1.0.0
*/
@Person(name="aaa",age=28)
public class AAA {
}
/**
*
* @author qxl
* @date 2016年11月23日 下午1:08:09
* @version 1.0.0
*/
@Person(name="xingoo",age=25)
public class Test3 {
public static void print(Class c){
System.out.println(c.getName());
//java.lang.Class的getAnnotation方法,如果有注解,则返回注解。否则返回null
Person person = (Person)c.getAnnotation(Person.class);
if(person != null){
System.out.println("name:"+person.name()+" age:"+person.age());
}else{
System.out.println("person unknown!");
}
}
public static void main(String[] args){
Test3.print(Test3.class);
Test3.print(AAA.class);
}
}