JDK5开始增加元数据支持,也就是Annotation
什么是元数据:
元数据又称中介数据、中继数据,为描述数据的数据,主要是描述数据属性的信息。
第一次见在Python的Django中,我在创建表单/model的时候可以看到有个叫做Meta的东西,他涉及到Python的类创建,简单的说就是给type()提供了一些变量和值。详细原理
http://blog.jobbole.com/21351/
回到Java
~Annotation其实是代码里的特殊标记,它们可以在编译、类加载、运行时被读取,在不改变原有逻辑的情况下,在源文件中补充信息。有些工具可以通过这些信息可以通过这些信息验证和部署。
Annotation,可以用来修饰包、类、构造器、方法、成员变量、参数、局部变量的声明。
.../java/lang/annotation/ElementType.java
Annotation是一个接口,可以使用反射来获取指定元素的Annotation对象,然后获取元数据
~四个基本注解-J7+
@Override重写/@Deprecated弃用/@SuppressWarnings抑制编译警告/@SafeVarargs堆污染警告,在java.lang下
1、@Override
用来只等方法重写,强制一个子类必须重写父类的方法。
它告诉编译器检查这个方法,保证父类要包含一个被改方法重写的方法,否则出错。
避免各种笔误
2、@Deprecated
用来表示某个元素(类、方法等)已经过时,使用时编译器会警告
3、@SuppressWarnings
取消显示指定的编译器警告,会作用于该程序的所有子元素
4、@SafeVarargs
堆污染
List list = new ArrayList<Integer>();
list.add(10);
List<String> temp = list;
~JDK的元Annotation
4个元注解用来修饰其他的Annotation定义
1. @Retention
保留时间
public enum RetentionPolicy {
/* Annotations are to be discarded by the compiler.* 编译时丢弃/
SOURCE,
/* Annotations are to be recorded in the class file by the compiler
* but need not be retained by the VM at run time. This is the default
* behavior.* 保留在calss文件中,JVM运行时丢弃/
CLASS,
/* Annotations are to be recorded in the class file by the compiler and
* retained by the VM at run time, so they may be read reflectively.
* @see java.lang.reflect.AnnotatedElement 保留在class文件中,JVM运行时也会保留,用反射读取*/
RUNTIME
}
2. @Target
修饰的目标
public enum ElementType {
/** Class, interface (including annotation type), or enum declaration */
TYPE,
/** Field declaration (includes enum constants) */
FIELD,
/** Method declaration */
METHOD,
/** Formal(adj.正式的;拘谨的;有条理的,[专业:形式{形参}]) parameter declaration */
PARAMETER,
/** Constructor declaration */
CONSTRUCTOR,
/** Local variable declaration */
LOCAL_VARIABLE,
/** Annotation type declaration */
ANNOTATION_TYPE,
/** Package declaration */
PACKAGE,
/**Type parameter declaration
* @since 1.8*/
TYPE_PARAMETER,
/**Use of a type
* @since 1.8*/
TYPE_USE
}
3. @Documented
将被javadoc工具提取成文档
4. @Inherited
子类将会继承注解的修饰
~自定义Annotation
public @interface 名字{
[type name()[default value];//成员变量以方法的形式来定义]...
}
根据Annotation是否包含成员变量可以分成2种。
1、标记Annotation:没有定义成员变量,利用自身存在与否提供信息如@Override
2、元数据Annotation:包含成员变量
~提取Annotation
(1)利用对象调用getClass()方法获得Class实例
(2)利用Class类的静态的forName()方法,使用类名获得Class实例
(3)运用.class的方式获得Class实例,如:类名.class
//类对象.getClass().getMethod("必须是用public标识的方法").getAnnotations())
Annotation[] aArray = Class.forName("类名").getMethod("必须是public标识的方法").getAnnotations();
但是要注意的是只有public标识的才可以,包括默认包行为的都不可以
to be continue;