Java annotation的实例是什么类的?
Java里annotation看起来就像接口一般。如果跟接口一样的话,那肯定不能直接生成实例。那通过反射API获得的那些annotation实例都是些什么东西呢?
那些annotation实例毫无疑问是Java对象。但它们到底是什么“类”的实例?是不是一定要在JVM内部提供特殊的支持?
Java的annotation没有行为,只能有数据,实际上就是一组键值对而已。通过解析(parse)Class文件就能把一个annotation需要的键值对都找出来。
于是问题就变成:
·有一个接口
·有一组键值对,它里面的数组能支持前面那个接口的功能
怎样才能把这个接口和这个map结合起来呢?
在OpenJDK 6里,sun.reflect.annotation.AnnotationParser的第254行:
/** * Returns an annotation of the given type backed by the given * member -> value map. */public static Annotation annotationForMap( Class type, Map<String, Object> memberValues){ return (Annotation) Proxy.newProxyInstance( type.getClassLoader(), new Class[] { type }, new AnnotationInvocationHandler(type, memberValues));}
/* * Provides a new annotation instance. * @param annotationType the annotation type definition * @param elements name-value pairs representing elements of the annotation * @return a new annotation instance */public static Annotation createAnnotation( Class<? extends Annotation> annotationType, AnnotationMember[] elements) { AnnotationFactory antn = new AnnotationFactory(annotationType, elements); return (Annotation)Proxy.newProxyInstance( annotationType.getClassLoader(), new Class[]{annotationType}, antn);}