You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

AnnotationImpl.java 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. /*
  2. * Javassist, a Java-bytecode translator toolkit.
  3. * Copyright (C) 1999- Shigeru Chiba. All Rights Reserved.
  4. *
  5. * The contents of this file are subject to the Mozilla Public License Version
  6. * 1.1 (the "License"); you may not use this file except in compliance with
  7. * the License. Alternatively, the contents of this file may be used under
  8. * the terms of the GNU Lesser General Public License Version 2.1 or later,
  9. * or the Apache License Version 2.0.
  10. *
  11. * Software distributed under the License is distributed on an "AS IS" basis,
  12. * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  13. * for the specific language governing rights and limitations under the
  14. * License.
  15. */
  16. package javassist.bytecode.annotation;
  17. import java.lang.reflect.InvocationHandler;
  18. import java.lang.reflect.Method;
  19. import java.lang.reflect.Proxy;
  20. import javassist.ClassPool;
  21. import javassist.CtClass;
  22. import javassist.NotFoundException;
  23. import javassist.bytecode.AnnotationDefaultAttribute;
  24. import javassist.bytecode.ClassFile;
  25. import javassist.bytecode.MethodInfo;
  26. /**
  27. * Internal-use only. This is a helper class internally used for implementing
  28. * <code>toAnnotationType()</code> in <code>Annotation</code>.
  29. *
  30. * @author Shigeru Chiba
  31. * @author <a href="mailto:bill@jboss.org">Bill Burke</a>
  32. * @author <a href="mailto:adrian@jboss.org">Adrian Brock</a>
  33. */
  34. public class AnnotationImpl implements InvocationHandler {
  35. private static final String JDK_ANNOTATION_CLASS_NAME = "java.lang.annotation.Annotation";
  36. private static Method JDK_ANNOTATION_TYPE_METHOD = null;
  37. private Annotation annotation;
  38. private ClassPool pool;
  39. private ClassLoader classLoader;
  40. private transient Class annotationType;
  41. private transient int cachedHashCode = Integer.MIN_VALUE;
  42. static {
  43. // Try to resolve the JDK annotation type method
  44. try {
  45. Class clazz = Class.forName(JDK_ANNOTATION_CLASS_NAME);
  46. JDK_ANNOTATION_TYPE_METHOD = clazz.getMethod("annotationType", (Class[])null);
  47. }
  48. catch (Exception ignored) {
  49. // Probably not JDK5+
  50. }
  51. }
  52. /**
  53. * Constructs an annotation object.
  54. *
  55. * @param cl class loader for obtaining annotation types.
  56. * @param clazz the annotation type.
  57. * @param cp class pool for containing an annotation
  58. * type (or null).
  59. * @param anon the annotation.
  60. * @return the annotation
  61. */
  62. public static Object make(ClassLoader cl, Class clazz, ClassPool cp,
  63. Annotation anon) {
  64. AnnotationImpl handler = new AnnotationImpl(anon, cp, cl);
  65. return Proxy.newProxyInstance(cl, new Class[] { clazz }, handler);
  66. }
  67. private AnnotationImpl(Annotation a, ClassPool cp, ClassLoader loader) {
  68. annotation = a;
  69. pool = cp;
  70. classLoader = loader;
  71. }
  72. /**
  73. * Obtains the name of the annotation type.
  74. *
  75. * @return the type name
  76. */
  77. public String getTypeName() {
  78. return annotation.getTypeName();
  79. }
  80. /**
  81. * Get the annotation type
  82. *
  83. * @return the annotation class
  84. * @throws NoClassDefFoundError when the class could not loaded
  85. */
  86. private Class getAnnotationType() {
  87. if (annotationType == null) {
  88. String typeName = annotation.getTypeName();
  89. try {
  90. annotationType = classLoader.loadClass(typeName);
  91. }
  92. catch (ClassNotFoundException e) {
  93. NoClassDefFoundError error = new NoClassDefFoundError("Error loading annotation class: " + typeName);
  94. error.setStackTrace(e.getStackTrace());
  95. throw error;
  96. }
  97. }
  98. return annotationType;
  99. }
  100. /**
  101. * Obtains the internal data structure representing the annotation.
  102. *
  103. * @return the annotation
  104. */
  105. public Annotation getAnnotation() {
  106. return annotation;
  107. }
  108. /**
  109. * Executes a method invocation on a proxy instance.
  110. * The implementations of <code>toString()</code>, <code>equals()</code>,
  111. * and <code>hashCode()</code> are directly supplied by the
  112. * <code>AnnotationImpl</code>. The <code>annotationType()</code> method
  113. * is also available on the proxy instance.
  114. */
  115. public Object invoke(Object proxy, Method method, Object[] args)
  116. throws Throwable
  117. {
  118. String name = method.getName();
  119. if (Object.class == method.getDeclaringClass()) {
  120. if ("equals".equals(name)) {
  121. Object obj = args[0];
  122. return new Boolean(checkEquals(obj));
  123. }
  124. else if ("toString".equals(name))
  125. return annotation.toString();
  126. else if ("hashCode".equals(name))
  127. return new Integer(hashCode());
  128. }
  129. else if ("annotationType".equals(name)
  130. && method.getParameterTypes().length == 0)
  131. return getAnnotationType();
  132. MemberValue mv = annotation.getMemberValue(name);
  133. if (mv == null)
  134. return getDefault(name, method);
  135. else
  136. return mv.getValue(classLoader, pool, method);
  137. }
  138. private Object getDefault(String name, Method method)
  139. throws ClassNotFoundException, RuntimeException
  140. {
  141. String classname = annotation.getTypeName();
  142. if (pool != null) {
  143. try {
  144. CtClass cc = pool.get(classname);
  145. ClassFile cf = cc.getClassFile2();
  146. MethodInfo minfo = cf.getMethod(name);
  147. if (minfo != null) {
  148. AnnotationDefaultAttribute ainfo
  149. = (AnnotationDefaultAttribute)
  150. minfo.getAttribute(AnnotationDefaultAttribute.tag);
  151. if (ainfo != null) {
  152. MemberValue mv = ainfo.getDefaultValue();
  153. return mv.getValue(classLoader, pool, method);
  154. }
  155. }
  156. }
  157. catch (NotFoundException e) {
  158. throw new RuntimeException("cannot find a class file: "
  159. + classname);
  160. }
  161. }
  162. throw new RuntimeException("no default value: " + classname + "."
  163. + name + "()");
  164. }
  165. /**
  166. * Returns a hash code value for this object.
  167. */
  168. public int hashCode() {
  169. if (cachedHashCode == Integer.MIN_VALUE) {
  170. int hashCode = 0;
  171. // Load the annotation class
  172. getAnnotationType();
  173. Method[] methods = annotationType.getDeclaredMethods();
  174. for (int i = 0; i < methods.length; ++ i) {
  175. String name = methods[i].getName();
  176. int valueHashCode = 0;
  177. // Get the value
  178. MemberValue mv = annotation.getMemberValue(name);
  179. Object value = null;
  180. try {
  181. if (mv != null)
  182. value = mv.getValue(classLoader, pool, methods[i]);
  183. if (value == null)
  184. value = getDefault(name, methods[i]);
  185. }
  186. catch (RuntimeException e) {
  187. throw e;
  188. }
  189. catch (Exception e) {
  190. throw new RuntimeException("Error retrieving value " + name + " for annotation " + annotation.getTypeName(), e);
  191. }
  192. // Calculate the hash code
  193. if (value != null) {
  194. if (value.getClass().isArray())
  195. valueHashCode = arrayHashCode(value);
  196. else
  197. valueHashCode = value.hashCode();
  198. }
  199. hashCode += 127 * name.hashCode() ^ valueHashCode;
  200. }
  201. cachedHashCode = hashCode;
  202. }
  203. return cachedHashCode;
  204. }
  205. /**
  206. * Check that another annotation equals ourselves.
  207. *
  208. * @param obj the other annotation
  209. * @return the true when equals false otherwise
  210. * @throws Exception for any problem
  211. */
  212. private boolean checkEquals(Object obj) throws Exception {
  213. if (obj == null)
  214. return false;
  215. // Optimization when the other is one of ourselves
  216. if (obj instanceof Proxy) {
  217. InvocationHandler ih = Proxy.getInvocationHandler(obj);
  218. if (ih instanceof AnnotationImpl) {
  219. AnnotationImpl other = (AnnotationImpl) ih;
  220. return annotation.equals(other.annotation);
  221. }
  222. }
  223. Class otherAnnotationType = (Class) JDK_ANNOTATION_TYPE_METHOD.invoke(obj, (Object[])null);
  224. if (getAnnotationType().equals(otherAnnotationType) == false)
  225. return false;
  226. Method[] methods = annotationType.getDeclaredMethods();
  227. for (int i = 0; i < methods.length; ++ i) {
  228. String name = methods[i].getName();
  229. // Get the value
  230. MemberValue mv = annotation.getMemberValue(name);
  231. Object value = null;
  232. Object otherValue = null;
  233. try {
  234. if (mv != null)
  235. value = mv.getValue(classLoader, pool, methods[i]);
  236. if (value == null)
  237. value = getDefault(name, methods[i]);
  238. otherValue = methods[i].invoke(obj, (Object[])null);
  239. }
  240. catch (RuntimeException e) {
  241. throw e;
  242. }
  243. catch (Exception e) {
  244. throw new RuntimeException("Error retrieving value " + name + " for annotation " + annotation.getTypeName(), e);
  245. }
  246. if (value == null && otherValue != null)
  247. return false;
  248. if (value != null && value.equals(otherValue) == false)
  249. return false;
  250. }
  251. return true;
  252. }
  253. /**
  254. * Calculates the hashCode of an array using the same
  255. * algorithm as java.util.Arrays.hashCode()
  256. *
  257. * @param object the object
  258. * @return the hashCode
  259. */
  260. private static int arrayHashCode(Object object)
  261. {
  262. if (object == null)
  263. return 0;
  264. int result = 1;
  265. Object[] array = (Object[]) object;
  266. for (int i = 0; i < array.length; ++i) {
  267. int elementHashCode = 0;
  268. if (array[i] != null)
  269. elementHashCode = array[i].hashCode();
  270. result = 31 * result + elementHashCode;
  271. }
  272. return result;
  273. }
  274. }