annotation的学习
1.target指明了能标注在哪些类型上面: 语法是@Target(ElementType.type) 其中它的参数可以是: A.type表示的是标注在类和借口上的注解。 B.Field表示的是标注在属性上的注解。 C.Method表示的是标注在方法上的注解。 D.Paramenter表示的是标注在方法中的参数。 E.construct 表示的是标注在构造器上面的注解。 F.Annotation_type表示的是标注在注解上面的注解。 注意: 若想要次注解能标注在多个类型上面,则可以使用“,”隔开多个注解类型。
2.documented: 是否能够让我们定义的注解出现在帮助文档中。语法结构: @Documented
3.retention : 语法结构: @Retention(RetentionPolicy.source) 其中参数可以 是: A.source 表示的是该注解能够在原文件中起作用。 B.Class 表示的是这个注解在源文件和class中起作用。 C.runtime: 表示的是该注解在源文件,class文件,运行时都起作用。
4.注意在注解中能有很多属性,但是在使用时都必须使用。即在使用的时候就需要将属性都赋值。
5.注解解析器: 能够实现注解解析的类成为注解解析器。
过程: A. 首先将一个类放到class里面。 Class Student = Class.forName("类的全名");注意其中类的全名指的是使用了注解的类的全名,包括包名。
B.得到class之后, 使用方法获取该类中的Annotation。 例如: Name name = (Name)Student.getAnnotation(Name.Class); 其中Name为一个注解,且该注解用于表示类,通过getAnnotation方法为通过一个包含注解的类来获取注解类。
C.最后通过name.value()方法来验证一下是否正确。
源码展示:
注解类:
@Target(ElementType.TYPE)
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface Name{
String value();
}
使用类:
@Name(value="学生“)
public class Student(){
}
注解解析器:
public class StudentParse{
@test
public void parse() throw Exception{
Class StudentClass = Class.forName("Student");
Name name = (Name)StudentClass.getAnnotation(Name.Class);
System.out.println(name.value());
}