首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

Java annotation的范例是什么类的

2012-11-09 
Java annotation的实例是什么类的?Java里annotation看起来就像接口一般。如果跟接口一样的话,那肯定不能直

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));}

(Oracle/Sun JDK 6同理)
这边的实现在HotSpot VM内部没啥特别支持,基本上就是在Java层把功能都实现出来了。

在Apache Harmony里,org.apache.harmony.lang.annotation.AnnotationFactory的第195行
/* * 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);}

DRLVM周边的用于支持JDK核心类的native代码里确实有一些用来支持annotation的部分,但并不是在DRLVM的核心里的。也就是说在JVM内部也没有为创建实际的annotation“类”提供特别功能。而且给人的感觉是它纯粹是为了避开与Sun JDK的相似性才用了这么奇怪的设计…

虽然具体实现不同,但两者都用了动态代理。很直观对吧?

当然这不是唯一解法。我只是想说,首先不必纠结annotation到底是什么“类”的实例,反正背后多半就是个代理而已;其次,源码就在哪里,如果是针对某个实现想了解更多的话自己很容易就能找到答案…
不,太麻烦了。除非有明确的问题点不然我不想拿这么“大”的题目来讲

热点排行