注解(Annotation)入门
1.@Target,
作用:用于描述注解的使用范围(即:被描述的注解可以用在什么地方)
取值(ElementType)有:
1.CONSTRUCTOR:用于描述构造器
2.FIELD:用于描述域
3.LOCAL_VARIABLE:用于描述局部变量
4.METHOD:用于描述方法
5.PACKAGE:用于描述包
6.PARAMETER:用于描述参数
7.TYPE:用于描述类、接口(包括注解类型) 或enum声明
2.@Retention
该注解描述了作用范围
1. java RetentionPolicy.SOURCE
2.java+class RetentionPolicy.CLASS
3. java+class+jvm RetentionPolicy.RUNTIME
3.@Documented用于描述其它类型的annotation应该被作为被标注的程序成员的公共API,因此可以被例如javadoc此类的工具文档化。Documented是一个标记注解,没有成员。
4.@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类型被发现,或者到达类继承结构的顶层。
一个小例子
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE,ElementType.METHOD})
@Documented//是否在帮助文档中出现
public @interface Name {
String value() default "";//Name注解有一个属性为value
}
@Name("reed1991")
public class Reed {
@Name("java学科")
public void java(){
System.out.println("很牛");
}
@Name("net学科")
public void net(){
System.out.println("也很牛");
}
}
注解解析代码
/**
* 注解解析器
* @author Administrator
*
*/
public class AnnotationParse {
public static void parse(){
Class classt = Reed.class;
/**
* 类上的注解
*/
if(classt.isAnnotationPresent(Name.class)){
Name name = (Name)classt.getAnnotation(Name.class);
System.out.println(name.value());
}
Method[] methods = classt.getMethods();
for(Method method:methods){
if(method.isAnnotationPresent(Name.class)){
Name name = (Name)method.getAnnotation(Name.class);
System.out.println(name.value());
}
}
}
@Test
public void test(){
AnnotationParse.parse();
}
}
输出:
reed1991
java学科
net学科
如果 String value() default "reed1991 " 默认值写成reed1991
那么@Name(" ")里面可以为空