AnnotationEntry.java 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. // Copyright (c) 2010 Per M.A. Bothner.
  2. // This is free software; for terms and warranty disclaimer see ./COPYING.
  3. package gnu.bytecode;
  4. import java.util.*;
  5. import java.lang.reflect.Array;
  6. import java.lang.reflect.Proxy;
  7. import java.lang.annotation.*;
  8. /* #ifdef use:javax.lang.model */
  9. import javax.lang.model.element.*;
  10. /* #endif */
  11. /** An annotation value mirror. */
  12. public class AnnotationEntry
  13. implements java.lang.reflect.InvocationHandler
  14. /* #ifdef JAVA5 */
  15. , java.lang.annotation.Annotation
  16. /* #endif */
  17. /* #ifdef use:javax.lang.model */
  18. /* FUTURE also implements: javax.lang.model.element.AnnotationMirror */
  19. /* #endif */
  20. {
  21. ClassType annotationType;
  22. int annotationTypeIndex;
  23. public RetentionPolicy getRetention ()
  24. {
  25. Annotation retention = getAnnotationType().getReflectClass()
  26. .getAnnotation(Retention.class);
  27. if (retention == null)
  28. return RetentionPolicy.CLASS;
  29. return ((Retention) retention).value();
  30. }
  31. /** Is there is a {@code @Target} meta-annotation that includes the parameter?
  32. * If the annotationType has no {@code @Target} meta-annotation, return true,
  33. * since in that case the annotation type is allowed in all contexts.
  34. * If {@code etype==null}, return false iff there is a {@code @Target} meta-annotation.
  35. */
  36. public boolean hasTarget (ElementType etype)
  37. {
  38. Annotation target = getAnnotationType().getReflectClass()
  39. .getAnnotation(Target.class);
  40. if (target == null)
  41. return true;
  42. if (etype != null)
  43. {
  44. ElementType[] etypes = (ElementType[]) ((Target) target).value();
  45. for (int i = etypes.length; --i >= 0; )
  46. if (etypes[i] == etype)
  47. return true;
  48. }
  49. return false;
  50. }
  51. public AnnotationEntry ()
  52. {
  53. }
  54. public AnnotationEntry (ClassType annotationType)
  55. {
  56. this.annotationType = annotationType;
  57. }
  58. LinkedHashMap<String,Value> elementsValue = new LinkedHashMap<String,Value>(10);
  59. public ClassType getAnnotationType ()
  60. {
  61. return annotationType;
  62. }
  63. public void addMember(String name, Value value)
  64. {
  65. elementsValue.put(name, value);
  66. }
  67. public void addMember(String name, Object value, Type type)
  68. {
  69. elementsValue.put(name, asAnnotationValue(value, type));
  70. }
  71. public static Value asAnnotationValue(Object val, Type type)
  72. {
  73. String sig = type.getSignature();
  74. char kind = sig.charAt(0);
  75. switch (kind)
  76. {
  77. case 'B': val= ((Number) val).byteValue(); break;
  78. case 'S': val= ((Number) val).shortValue(); break;
  79. case 'I': val= ((Number) val).intValue(); break;
  80. case 'J': val = ((Number) val).longValue(); break;
  81. case 'L':
  82. if (sig.equals("Ljava/lang/String;"))
  83. {
  84. kind = 's';
  85. val = ((CharSequence) val).toString();
  86. }
  87. else if (sig.equals("Ljava/lang/Class;"))
  88. {
  89. kind = 'c';
  90. if (val instanceof Type)
  91. val = (Type) val;
  92. else
  93. val = Type.make((Class) val);
  94. }
  95. else if (((ClassType) type).isSubclass("java.lang.Enum"))
  96. {
  97. kind = 'e';
  98. }
  99. else if (((ClassType) type).implementsInterface(Type.javalangannotationAnnotationType))
  100. {
  101. kind = '@';
  102. val = (AnnotationEntry) Proxy.getInvocationHandler(val);
  103. }
  104. break;
  105. case '[':
  106. Type eltype = ((ArrayType) type).getComponentType();
  107. List<AnnotationEntry.Value> alist = new ArrayList<AnnotationEntry.Value>();
  108. if (val instanceof List<?>)
  109. {
  110. List<?> lst = (List<?>) val;
  111. int len = lst.size();
  112. for (int i = 0; i < len; i++)
  113. alist.add(asAnnotationValue(lst.get(i), eltype));
  114. }
  115. else
  116. {
  117. int len = Array.getLength(val);
  118. for (int i = 0; i < len; i++)
  119. alist.add(asAnnotationValue(Array.get(val, i), eltype));
  120. }
  121. val = alist;
  122. break;
  123. }
  124. return new AnnotationEntry.Value(kind, type, val);
  125. }
  126. /* #ifdef JAVA5 */
  127. @SuppressWarnings("unchecked")
  128. /* #endif */
  129. public Class<? extends java.lang.annotation.Annotation> annotationType ()
  130. {
  131. return (Class<? extends java.lang.annotation.Annotation>) annotationType.getReflectClass();
  132. }
  133. /* FUTURE
  134. public Map<Member,AnnotationValue> getElementValues()
  135. {
  136. convert from elementsValue;
  137. }
  138. */
  139. public boolean equals(Object obj)
  140. {
  141. if (! (obj instanceof AnnotationEntry))
  142. return false;
  143. AnnotationEntry other = (AnnotationEntry) obj;
  144. if (! getAnnotationType().getName().equals(other.getAnnotationType().getName()))
  145. return false;
  146. for (Map.Entry<String,Value> it : elementsValue.entrySet())
  147. {
  148. String key = it.getKey();
  149. Value value1 = it.getValue();
  150. Value value2 = other.elementsValue.get(key);
  151. if (value1 != value2)
  152. {
  153. if (value1 == null || value2 == null
  154. || ! value1.equals(value2))
  155. return false;
  156. }
  157. }
  158. for (Map.Entry<String,Value> it : other.elementsValue.entrySet())
  159. {
  160. String key = it.getKey();
  161. Object value2 = it.getValue();
  162. Object value1 = elementsValue.get(key);
  163. if (value1 != value2)
  164. {
  165. if (value1 == null || value2 == null
  166. || ! value1.equals(value2))
  167. return false;
  168. }
  169. }
  170. return true;
  171. }
  172. public int hashCode()
  173. {
  174. int hash = 0;
  175. // Note the Annotation spec requires we also include the
  176. // hashCode of members with default values; I don't think we do that.
  177. for (Map.Entry<String,Value> it : elementsValue.entrySet())
  178. {
  179. int khash = it.getKey().hashCode();
  180. int vhash = it.getValue().hashCode();
  181. hash += 127 * khash ^ vhash;
  182. }
  183. return hash;
  184. }
  185. public String toString()
  186. {
  187. StringBuilder sbuf = new StringBuilder();
  188. sbuf.append('@');
  189. sbuf.append(getAnnotationType().getName());
  190. sbuf.append('(');
  191. int count = 0;
  192. for (Map.Entry<String,Value> it : elementsValue.entrySet())
  193. {
  194. if (count > 0)
  195. sbuf.append(", ");
  196. sbuf.append(it.getKey());
  197. sbuf.append('=');
  198. sbuf.append(it.getValue());
  199. count++;
  200. }
  201. sbuf.append(')');
  202. return sbuf.toString();
  203. }
  204. public void print (int indentation, ClassTypeWriter dst)
  205. {
  206. dst.printOptionalIndex(annotationTypeIndex);
  207. dst.print('@');
  208. String cname = annotationType != null ? annotationType.getSignature()
  209. : ((CpoolUtf8) dst.ctype.constants.getPoolEntry(annotationTypeIndex)).getString();
  210. Type.printSignature(cname, 0, cname.length(), dst);
  211. int count = elementsValue.size();
  212. indentation += 2;
  213. for (Map.Entry<String,Value> e : elementsValue.entrySet())
  214. {
  215. dst.println();
  216. String key = e.getKey();
  217. Value val = e.getValue();
  218. dst.printSpaces(indentation);
  219. dst.printOptionalIndex(val.nindex);
  220. dst.print(key);
  221. dst.print(" => ");
  222. val.print(indentation, dst);
  223. }
  224. }
  225. public Object invoke (Object proxy, java.lang.reflect.Method method, Object[] args)
  226. {
  227. String mname = method.getName();
  228. int nargs = args == null ? 0 : args.length;
  229. if (mname.equals("toString") && nargs == 0)
  230. return this.toString();
  231. if (mname.equals("hashCode") && nargs == 0)
  232. return this.hashCode();
  233. return elementsValue.get(mname).getValue();
  234. }
  235. public static class Value
  236. /* #ifdef use:javax.lang.model */
  237. implements AnnotationValue
  238. /* #endif */
  239. {
  240. Type type;
  241. /** Either one of the standard primitize signature code
  242. * B (byte), S (short), I (int) , J (long), F (float), D (double),
  243. * Z (boolean), C (char).
  244. * or:
  245. * 'e' (enum-constant)
  246. * '[' (array)
  247. * '@' (type)
  248. * 's' (string)
  249. * 'c' (string)
  250. */
  251. char kind;
  252. Object value;
  253. Object valuex;
  254. /** Indexes in ConstantPool of corresponding name. */
  255. int nindex;
  256. /** Indexes in ConstantPool, if non-zero. */
  257. int index1;
  258. int index2;
  259. public Value (char kind, Type type, Object value)
  260. {
  261. this.kind = kind;
  262. this.type = type;
  263. this.value = value;
  264. }
  265. /** Get an Object representing the annotation value.
  266. * If the kind is 'e', the value is *either* a Field or an 2-element
  267. * array [ClassName, EnumName] or the actual Enum value.
  268. * If kind is 'c', the value is *either* a ClassType or a String.
  269. */
  270. public Object getValue()
  271. {
  272. if (kind == '[')
  273. {
  274. if (valuex == null)
  275. {
  276. List<? extends AnnotationEntry.Value> lvalue =
  277. (List<? extends AnnotationEntry.Value>) value;
  278. int n = lvalue.size();
  279. Class eltype = type.getReflectClass().getComponentType();
  280. Object arr = Array.newInstance(eltype, n);
  281. for (int i = 0; i < n; i++)
  282. Array.set(arr, i, lvalue.get(i).getValue());
  283. valuex = arr;
  284. }
  285. return valuex;
  286. }
  287. else if (kind == 'e') {
  288. if (valuex == null) {
  289. if (value instanceof Enum) {
  290. valuex = value;
  291. } else {
  292. ClassType type;
  293. String name;
  294. if (value instanceof Field) {
  295. Field f = (Field) value;
  296. type = f.getDeclaringClass();
  297. name = f.getName();
  298. } else {
  299. String[] sarr = (String[]) value;
  300. type = (ClassType) Type.signatureToType(sarr[0]);
  301. name = sarr[1];
  302. }
  303. Class<?> clas = type.getReflectClass();
  304. Class<? extends Enum> eclas = clas.asSubclass(Enum.class);
  305. Enum val = Enum.valueOf(eclas, name);
  306. valuex = val;
  307. }
  308. }
  309. return valuex;
  310. }
  311. // FIXME other conversions needed?
  312. return value;
  313. }
  314. public String toString() { return getValue().toString(); }
  315. /* #ifdef use:javax.lang.model */
  316. public <R,P> R accept(AnnotationValueVisitor<R,P> v, P p)
  317. {
  318. switch (kind)
  319. {
  320. case 'Z': return v.visitBoolean(((Boolean) value).booleanValue(), p);
  321. case 'C': return v.visitChar(((Character) value).charValue(), p);
  322. case 'B': return v.visitByte(((Byte) value).byteValue(), p);
  323. case 'S': return v.visitShort(((Short) value).shortValue(), p);
  324. case 'I': return v.visitInt(((Integer) value).intValue(), p);
  325. case 'J': return v.visitLong(((Long) value).longValue(), p);
  326. case 'F': return v.visitFloat(((Float) value).floatValue(), p);
  327. case 'D': return v.visitDouble(((Double) value).doubleValue(), p);
  328. case 's': return v.visitString((String) value, p);
  329. case '[':
  330. return v.visitArray((List<? extends AnnotationValue>) value, p);
  331. case 'e': /* FIXME: return v.visitEnumConstant((Field) value, p);*/
  332. case '@':
  333. default:
  334. throw new UnsupportedOperationException();
  335. }
  336. }
  337. /* #endif */
  338. public void print (int indentation, ClassTypeWriter out)
  339. {
  340. if ((out.flags & ClassTypeWriter.PRINT_EXTRAS) != 0)
  341. {
  342. out.print("(kind:");
  343. if (kind >= 'A' && kind <= 'z')
  344. out.print(kind);
  345. else
  346. out.print((int) kind);
  347. out.print(") ");
  348. }
  349. int expected = 0;
  350. switch (kind)
  351. {
  352. case 'B':
  353. case 'I':
  354. case 'S':
  355. case 'C':
  356. case 'Z':
  357. case 'J':
  358. case 'D':
  359. case 'F':
  360. case 's': // String
  361. out.printOptionalIndex(out.getCpoolEntry(index1));
  362. if (value instanceof String)
  363. out.printQuotedString((String) value);
  364. else
  365. out.print(value.toString());
  366. break;
  367. case 'e': // enum constant
  368. String[] sarr = decodeEnumEntry(value);
  369. String cname = sarr[0];
  370. String ename = sarr[1];
  371. out.print("enum[");
  372. if ((out.flags & ClassTypeWriter.PRINT_EXTRAS) != 0)
  373. out.print("type:");
  374. out.printOptionalIndex(index1);
  375. Type.printSignature(cname, 0, cname.length(), out);
  376. if ((out.flags & ClassTypeWriter.PRINT_EXTRAS) != 0)
  377. out.print(" value:");
  378. else
  379. out.print(' ');
  380. out.printOptionalIndex(index2);
  381. out.print(ename);
  382. out.print("]");
  383. break;
  384. case 'c': // class
  385. out.printOptionalIndex(index1);
  386. cname = value instanceof String ? (String) value
  387. : ((ClassType) value).getSignature();
  388. Type.printSignature(cname, 0, cname.length(), out);
  389. break;
  390. case '@': // annotation type
  391. ((AnnotationEntry) value).print(indentation + 2, out);
  392. break;
  393. case '[': // array
  394. List<AnnotationEntry.Value> vals = (List<AnnotationEntry.Value>) value;
  395. int sz = vals.size();
  396. out.print("array length:");
  397. out.print(sz);
  398. for (int i = 0; i < sz; i++)
  399. {
  400. out.println();
  401. out.printSpaces(indentation + 2);
  402. out.print(i);
  403. out.print(": ");
  404. vals.get(i).print(indentation + 2, out);
  405. }
  406. break;
  407. }
  408. }
  409. }
  410. /** Return [type descriptor, field name]. */
  411. static String[] decodeEnumEntry(Object value) {
  412. if (value instanceof Field) {
  413. Field fld = (Field) value;
  414. return new String[]{
  415. fld.getDeclaringClass().getSignature(),
  416. fld.getName()};
  417. }
  418. else if (value instanceof Enum) {
  419. Enum evalue = (Enum) value;
  420. return new String[]{
  421. ClassType.nameToSignature(evalue.getDeclaringClass().getName()),
  422. evalue.name()};
  423. }
  424. else
  425. return (String[]) value;
  426. }
  427. }