1. /*
  2. * @(#)Method.java 1.50 04/06/22
  3. *
  4. * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. package java.lang.reflect;
  8. import sun.reflect.MethodAccessor;
  9. import sun.reflect.Reflection;
  10. import sun.reflect.generics.repository.MethodRepository;
  11. import sun.reflect.generics.factory.CoreReflectionFactory;
  12. import sun.reflect.generics.factory.GenericsFactory;
  13. import sun.reflect.generics.scope.MethodScope;
  14. import sun.reflect.annotation.AnnotationType;
  15. import sun.reflect.annotation.AnnotationParser;
  16. import java.lang.annotation.Annotation;
  17. import java.lang.annotation.AnnotationFormatError;
  18. import java.nio.ByteBuffer;
  19. import java.util.Map;
  20. /**
  21. * A <code>Method</code> provides information about, and access to, a single method
  22. * on a class or interface. The reflected method may be a class method
  23. * or an instance method (including an abstract method).
  24. *
  25. * <p>A <code>Method</code> permits widening conversions to occur when matching the
  26. * actual parameters to invoke with the underlying method's formal
  27. * parameters, but it throws an <code>IllegalArgumentException</code> if a
  28. * narrowing conversion would occur.
  29. *
  30. * @see Member
  31. * @see java.lang.Class
  32. * @see java.lang.Class#getMethods()
  33. * @see java.lang.Class#getMethod(String, Class[])
  34. * @see java.lang.Class#getDeclaredMethods()
  35. * @see java.lang.Class#getDeclaredMethod(String, Class[])
  36. *
  37. * @author Kenneth Russell
  38. * @author Nakul Saraiya
  39. */
  40. public final
  41. class Method extends AccessibleObject implements GenericDeclaration,
  42. Member {
  43. private Class clazz;
  44. private int slot;
  45. // This is guaranteed to be interned by the VM in the 1.4
  46. // reflection implementation
  47. private String name;
  48. private Class returnType;
  49. private Class[] parameterTypes;
  50. private Class[] exceptionTypes;
  51. private int modifiers;
  52. // Generics and annotations support
  53. private transient String signature;
  54. // generic info repository; lazily initialized
  55. private transient MethodRepository genericInfo;
  56. private byte[] annotations;
  57. private byte[] parameterAnnotations;
  58. private byte[] annotationDefault;
  59. private volatile MethodAccessor methodAccessor;
  60. // For sharing of MethodAccessors. This branching structure is
  61. // currently only two levels deep (i.e., one root Method and
  62. // potentially many Method objects pointing to it.)
  63. private Method root;
  64. // More complicated security check cache needed here than for
  65. // Class.newInstance() and Constructor.newInstance()
  66. private volatile Class securityCheckTargetClassCache;
  67. // Generics infrastructure
  68. private String getGenericSignature() {return signature;}
  69. // Accessor for factory
  70. private GenericsFactory getFactory() {
  71. // create scope and factory
  72. return CoreReflectionFactory.make(this, MethodScope.make(this));
  73. }
  74. // Accessor for generic info repository
  75. private MethodRepository getGenericInfo() {
  76. // lazily initialize repository if necessary
  77. if (genericInfo == null) {
  78. // create and cache generic info repository
  79. genericInfo = MethodRepository.make(getGenericSignature(),
  80. getFactory());
  81. }
  82. return genericInfo; //return cached repository
  83. }
  84. /**
  85. * Package-private constructor used by ReflectAccess to enable
  86. * instantiation of these objects in Java code from the java.lang
  87. * package via sun.reflect.LangReflectAccess.
  88. */
  89. Method(Class declaringClass,
  90. String name,
  91. Class[] parameterTypes,
  92. Class returnType,
  93. Class[] checkedExceptions,
  94. int modifiers,
  95. int slot,
  96. String signature,
  97. byte[] annotations,
  98. byte[] parameterAnnotations,
  99. byte[] annotationDefault)
  100. {
  101. this.clazz = declaringClass;
  102. this.name = name;
  103. this.parameterTypes = parameterTypes;
  104. this.returnType = returnType;
  105. this.exceptionTypes = checkedExceptions;
  106. this.modifiers = modifiers;
  107. this.slot = slot;
  108. this.signature = signature;
  109. this.annotations = annotations;
  110. this.parameterAnnotations = parameterAnnotations;
  111. this.annotationDefault = annotationDefault;
  112. }
  113. /**
  114. * Package-private routine (exposed to java.lang.Class via
  115. * ReflectAccess) which returns a copy of this Method. The copy's
  116. * "root" field points to this Method.
  117. */
  118. Method copy() {
  119. // This routine enables sharing of MethodAccessor objects
  120. // among Method objects which refer to the same underlying
  121. // method in the VM. (All of this contortion is only necessary
  122. // because of the "accessibility" bit in AccessibleObject,
  123. // which implicitly requires that new java.lang.reflect
  124. // objects be fabricated for each reflective call on Class
  125. // objects.)
  126. Method res = new Method(clazz, name, parameterTypes, returnType,
  127. exceptionTypes, modifiers, slot, signature,
  128. annotations, parameterAnnotations, annotationDefault);
  129. res.root = this;
  130. // Might as well eagerly propagate this if already present
  131. res.methodAccessor = methodAccessor;
  132. return res;
  133. }
  134. /**
  135. * Returns the <code>Class</code> object representing the class or interface
  136. * that declares the method represented by this <code>Method</code> object.
  137. */
  138. public Class<?> getDeclaringClass() {
  139. return clazz;
  140. }
  141. /**
  142. * Returns the name of the method represented by this <code>Method</code>
  143. * object, as a <code>String</code>.
  144. */
  145. public String getName() {
  146. return name;
  147. }
  148. /**
  149. * Returns the Java language modifiers for the method represented
  150. * by this <code>Method</code> object, as an integer. The <code>Modifier</code> class should
  151. * be used to decode the modifiers.
  152. *
  153. * @see Modifier
  154. */
  155. public int getModifiers() {
  156. return modifiers;
  157. }
  158. /**
  159. * Returns an array of <tt>TypeVariable</tt> objects that represent the
  160. * type variables declared by the generic declaration represented by this
  161. * <tt>GenericDeclaration</tt> object, in declaration order. Returns an
  162. * array of length 0 if the underlying generic declaration declares no type
  163. * variables.
  164. *
  165. * @return an array of <tt>TypeVariable</tt> objects that represent
  166. * the type variables declared by this generic declaration
  167. * @throws GenericSignatureFormatError if the generic
  168. * signature of this generic declaration does not conform to
  169. * the format specified in the Java Virtual Machine Specification,
  170. * 3rd edition
  171. * @since 1.5
  172. */
  173. public TypeVariable<Method>[] getTypeParameters() {
  174. if (getGenericSignature() != null)
  175. return (TypeVariable<Method>[])getGenericInfo().getTypeParameters();
  176. else
  177. return (TypeVariable<Method>[])new TypeVariable[0];
  178. }
  179. /**
  180. * Returns a <code>Class</code> object that represents the formal return type
  181. * of the method represented by this <code>Method</code> object.
  182. *
  183. * @return the return type for the method this object represents
  184. */
  185. public Class<?> getReturnType() {
  186. return returnType;
  187. }
  188. /**
  189. * Returns a <tt>Type</tt> object that represents the formal return
  190. * type of the method represented by this <tt>Method</tt> object.
  191. *
  192. * <p>If the return type is a parameterized type,
  193. * the <tt>Type</tt> object returned must accurately reflect
  194. * the actual type parameters used in the source code.
  195. *
  196. * <p>If the return type is a type variable or a parameterized type, it
  197. * is created. Otherwise, it is resolved.
  198. *
  199. * @return a <tt>Type</tt> object that represents the formal return
  200. * type of the underlying method
  201. * @throws GenericSignatureFormatError
  202. * if the generic method signature does not conform to the format
  203. * specified in the Java Virtual Machine Specification, 3rd edition
  204. * @throws TypeNotPresentException if the underlying method's
  205. * return type refers to a non-existent type declaration
  206. * @throws MalformedParameterizedTypeException if the
  207. * underlying method's return typed refers to a parameterized
  208. * type that cannot be instantiated for any reason
  209. * @since 1.5
  210. */
  211. public Type getGenericReturnType() {
  212. if (getGenericSignature() != null) {
  213. return getGenericInfo().getReturnType();
  214. } else { return getReturnType();}
  215. }
  216. /**
  217. * Returns an array of <code>Class</code> objects that represent the formal
  218. * parameter types, in declaration order, of the method
  219. * represented by this <code>Method</code> object. Returns an array of length
  220. * 0 if the underlying method takes no parameters.
  221. *
  222. * @return the parameter types for the method this object
  223. * represents
  224. */
  225. public Class<?>[] getParameterTypes() {
  226. return (Class<?>[]) parameterTypes.clone();
  227. }
  228. /**
  229. * Returns an array of <tt>Type</tt> objects that represent the formal
  230. * parameter types, in declaration order, of the method represented by
  231. * this <tt>Method</tt> object. Returns an array of length 0 if the
  232. * underlying method takes no parameters.
  233. *
  234. * <p>If a formal parameter type is a parameterized type,
  235. * the <tt>Type</tt> object returned for it must accurately reflect
  236. * the actual type parameters used in the source code.
  237. *
  238. * <p>If a formal parameter type is a type variable or a parameterized
  239. * type, it is created. Otherwise, it is resolved.
  240. *
  241. * @return an array of Types that represent the formal
  242. * parameter types of the underlying method, in declaration order
  243. * @throws GenericSignatureFormatError
  244. * if the generic method signature does not conform to the format
  245. * specified in the Java Virtual Machine Specification, 3rd edition
  246. * @throws TypeNotPresentException if any of the parameter
  247. * types of the underlying method refers to a non-existent type
  248. * declaration
  249. * @throws MalformedParameterizedTypeException if any of
  250. * the underlying method's parameter types refer to a parameterized
  251. * type that cannot be instantiated for any reason
  252. * @since 1.5
  253. */
  254. public Type[] getGenericParameterTypes() {
  255. if (getGenericSignature() != null)
  256. return getGenericInfo().getParameterTypes();
  257. else
  258. return getParameterTypes();
  259. }
  260. /**
  261. * Returns an array of <code>Class</code> objects that represent
  262. * the types of the exceptions declared to be thrown
  263. * by the underlying method
  264. * represented by this <code>Method</code> object. Returns an array of length
  265. * 0 if the method declares no exceptions in its <code>throws</code> clause.
  266. *
  267. * @return the exception types declared as being thrown by the
  268. * method this object represents
  269. */
  270. public Class<?>[] getExceptionTypes() {
  271. return (Class<?>[]) exceptionTypes.clone();
  272. }
  273. /**
  274. * Returns an array of <tt>Type</tt> objects that represent the
  275. * exceptions declared to be thrown by this <tt>Method</tt> object.
  276. * Returns an array of length 0 if the underlying method declares
  277. * no exceptions in its <tt>throws</tt> clause.
  278. *
  279. * <p>If an exception type is a parameterized type, the <tt>Type</tt>
  280. * object returned for it must accurately reflect the actual type
  281. * parameters used in the source code.
  282. *
  283. * <p>If an exception type is a type variable or a parameterized
  284. * type, it is created. Otherwise, it is resolved.
  285. *
  286. * @return an array of Types that represent the exception types
  287. * thrown by the underlying method
  288. * @throws GenericSignatureFormatError
  289. * if the generic method signature does not conform to the format
  290. * specified in the Java Virtual Machine Specification, 3rd edition
  291. * @throws TypeNotPresentException if the underlying method's
  292. * <tt>throws</tt> clause refers to a non-existent type declaration
  293. * @throws MalformedParameterizedTypeException if
  294. * the underlying method's <tt>throws</tt> clause refers to a
  295. * parameterized type that cannot be instantiated for any reason
  296. * @since 1.5
  297. */
  298. public Type[] getGenericExceptionTypes() {
  299. Type[] result;
  300. if (getGenericSignature() != null &&
  301. ((result = getGenericInfo().getExceptionTypes()).length > 0))
  302. return result;
  303. else
  304. return getExceptionTypes();
  305. }
  306. /**
  307. * Compares this <code>Method</code> against the specified object. Returns
  308. * true if the objects are the same. Two <code>Methods</code> are the same if
  309. * they were declared by the same class and have the same name
  310. * and formal parameter types and return type.
  311. */
  312. public boolean equals(Object obj) {
  313. if (obj != null && obj instanceof Method) {
  314. Method other = (Method)obj;
  315. if ((getDeclaringClass() == other.getDeclaringClass())
  316. && (getName() == other.getName())) {
  317. if (!returnType.equals(other.getReturnType()))
  318. return false;
  319. /* Avoid unnecessary cloning */
  320. Class[] params1 = parameterTypes;
  321. Class[] params2 = other.parameterTypes;
  322. if (params1.length == params2.length) {
  323. for (int i = 0; i < params1.length; i++) {
  324. if (params1[i] != params2[i])
  325. return false;
  326. }
  327. return true;
  328. }
  329. }
  330. }
  331. return false;
  332. }
  333. /**
  334. * Returns a hashcode for this <code>Method</code>. The hashcode is computed
  335. * as the exclusive-or of the hashcodes for the underlying
  336. * method's declaring class name and the method's name.
  337. */
  338. public int hashCode() {
  339. return getDeclaringClass().getName().hashCode() ^ getName().hashCode();
  340. }
  341. /**
  342. * Returns a string describing this <code>Method</code>. The string is
  343. * formatted as the method access modifiers, if any, followed by
  344. * the method return type, followed by a space, followed by the
  345. * class declaring the method, followed by a period, followed by
  346. * the method name, followed by a parenthesized, comma-separated
  347. * list of the method's formal parameter types. If the method
  348. * throws checked exceptions, the parameter list is followed by a
  349. * space, followed by the word throws followed by a
  350. * comma-separated list of the thrown exception types.
  351. * For example:
  352. * <pre>
  353. * public boolean java.lang.Object.equals(java.lang.Object)
  354. * </pre>
  355. *
  356. * <p>The access modifiers are placed in canonical order as
  357. * specified by "The Java Language Specification". This is
  358. * <tt>public</tt>, <tt>protected</tt> or <tt>private</tt> first,
  359. * and then other modifiers in the following order:
  360. * <tt>abstract</tt>, <tt>static</tt>, <tt>final</tt>,
  361. * <tt>synchronized</tt> <tt>native</tt>.
  362. */
  363. public String toString() {
  364. try {
  365. StringBuffer sb = new StringBuffer();
  366. int mod = getModifiers();
  367. if (mod != 0) {
  368. sb.append(Modifier.toString(mod) + " ");
  369. }
  370. sb.append(Field.getTypeName(getReturnType()) + " ");
  371. sb.append(Field.getTypeName(getDeclaringClass()) + ".");
  372. sb.append(getName() + "(");
  373. Class[] params = parameterTypes; // avoid clone
  374. for (int j = 0; j < params.length; j++) {
  375. sb.append(Field.getTypeName(params[j]));
  376. if (j < (params.length - 1))
  377. sb.append(",");
  378. }
  379. sb.append(")");
  380. Class[] exceptions = exceptionTypes; // avoid clone
  381. if (exceptions.length > 0) {
  382. sb.append(" throws ");
  383. for (int k = 0; k < exceptions.length; k++) {
  384. sb.append(exceptions[k].getName());
  385. if (k < (exceptions.length - 1))
  386. sb.append(",");
  387. }
  388. }
  389. return sb.toString();
  390. } catch (Exception e) {
  391. return "<" + e + ">";
  392. }
  393. }
  394. /**
  395. * Returns a string describing this <code>Method</code>, including
  396. * type parameters. The string is formatted as the method access
  397. * modifiers, if any, followed by an angle-bracketed
  398. * comma-separated list of the method's type parameters, if any,
  399. * followed by the method's generic return type, followed by a
  400. * space, followed by the class declaring the method, followed by
  401. * a period, followed by the method name, followed by a
  402. * parenthesized, comma-separated list of the method's generic
  403. * formal parameter types. A space is used to separate access
  404. * modifiers from one another and from the type parameters or
  405. * return type. If there are no type parameters, the type
  406. * parameter list is elided; if the type parameter list is
  407. * present, a space separates the list from the class name. If
  408. * the method is declared to throw exceptions, the parameter list
  409. * is followed by a space, followed by the word throws followed by
  410. * a comma-separated list of the generic thrown exception types.
  411. * If there are no type parameters, the type parameter list is
  412. * elided.
  413. *
  414. * <p>The access modifiers are placed in canonical order as
  415. * specified by "The Java Language Specification". This is
  416. * <tt>public</tt>, <tt>protected</tt> or <tt>private</tt> first,
  417. * and then other modifiers in the following order:
  418. * <tt>abstract</tt>, <tt>static</tt>, <tt>final</tt>,
  419. * <tt>synchronized</tt> <tt>native</tt>.
  420. *
  421. * @return a string describing this <code>Method</code>,
  422. * include type parameters
  423. *
  424. * @since 1.5
  425. */
  426. public String toGenericString() {
  427. try {
  428. StringBuilder sb = new StringBuilder();
  429. int mod = getModifiers();
  430. if (mod != 0) {
  431. sb.append(Modifier.toString(mod) + " ");
  432. }
  433. Type[] typeparms = getTypeParameters();
  434. if (typeparms.length > 0) {
  435. boolean first = true;
  436. sb.append("<");
  437. for(Type typeparm: typeparms) {
  438. if (!first)
  439. sb.append(",");
  440. if (typeparm instanceof Class)
  441. sb.append(((Class)typeparm).getName());
  442. else
  443. sb.append(typeparm.toString());
  444. first = false;
  445. }
  446. sb.append("> ");
  447. }
  448. Type genRetType = getGenericReturnType();
  449. sb.append( ((genRetType instanceof Class)?
  450. Field.getTypeName((Class)genRetType):genRetType.toString()) + " ");
  451. sb.append(Field.getTypeName(getDeclaringClass()) + ".");
  452. sb.append(getName() + "(");
  453. Type[] params = getGenericParameterTypes();
  454. for (int j = 0; j < params.length; j++) {
  455. sb.append((params[j] instanceof Class)?
  456. Field.getTypeName((Class)params[j]):
  457. (params[j].toString()) );
  458. if (j < (params.length - 1))
  459. sb.append(",");
  460. }
  461. sb.append(")");
  462. Type[] exceptions = getGenericExceptionTypes();
  463. if (exceptions.length > 0) {
  464. sb.append(" throws ");
  465. for (int k = 0; k < exceptions.length; k++) {
  466. sb.append((exceptions[k] instanceof Class)?
  467. ((Class)exceptions[k]).getName():
  468. exceptions[k].toString());
  469. if (k < (exceptions.length - 1))
  470. sb.append(",");
  471. }
  472. }
  473. return sb.toString();
  474. } catch (Exception e) {
  475. return "<" + e + ">";
  476. }
  477. }
  478. /**
  479. * Invokes the underlying method represented by this <code>Method</code>
  480. * object, on the specified object with the specified parameters.
  481. * Individual parameters are automatically unwrapped to match
  482. * primitive formal parameters, and both primitive and reference
  483. * parameters are subject to method invocation conversions as
  484. * necessary.
  485. *
  486. * <p>If the underlying method is static, then the specified <code>obj</code>
  487. * argument is ignored. It may be null.
  488. *
  489. * <p>If the number of formal parameters required by the underlying method is
  490. * 0, the supplied <code>args</code> array may be of length 0 or null.
  491. *
  492. * <p>If the underlying method is an instance method, it is invoked
  493. * using dynamic method lookup as documented in The Java Language
  494. * Specification, Second Edition, section 15.12.4.4; in particular,
  495. * overriding based on the runtime type of the target object will occur.
  496. *
  497. * <p>If the underlying method is static, the class that declared
  498. * the method is initialized if it has not already been initialized.
  499. *
  500. * <p>If the method completes normally, the value it returns is
  501. * returned to the caller of invoke; if the value has a primitive
  502. * type, it is first appropriately wrapped in an object. However,
  503. * if the value has the type of an array of a primitive type, the
  504. * elements of the array are <i>not</i> wrapped in objects; in
  505. * other words, an array of primitive type is returned. If the
  506. * underlying method return type is void, the invocation returns
  507. * null.
  508. *
  509. * @param obj the object the underlying method is invoked from
  510. * @param args the arguments used for the method call
  511. * @return the result of dispatching the method represented by
  512. * this object on <code>obj</code> with parameters
  513. * <code>args</code>
  514. *
  515. * @exception IllegalAccessException if this <code>Method</code> object
  516. * enforces Java language access control and the underlying
  517. * method is inaccessible.
  518. * @exception IllegalArgumentException if the method is an
  519. * instance method and the specified object argument
  520. * is not an instance of the class or interface
  521. * declaring the underlying method (or of a subclass
  522. * or implementor thereof); if the number of actual
  523. * and formal parameters differ; if an unwrapping
  524. * conversion for primitive arguments fails; or if,
  525. * after possible unwrapping, a parameter value
  526. * cannot be converted to the corresponding formal
  527. * parameter type by a method invocation conversion.
  528. * @exception InvocationTargetException if the underlying method
  529. * throws an exception.
  530. * @exception NullPointerException if the specified object is null
  531. * and the method is an instance method.
  532. * @exception ExceptionInInitializerError if the initialization
  533. * provoked by this method fails.
  534. */
  535. public Object invoke(Object obj, Object... args)
  536. throws IllegalAccessException, IllegalArgumentException,
  537. InvocationTargetException
  538. {
  539. if (!override) {
  540. if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
  541. Class caller = Reflection.getCallerClass(1);
  542. Class targetClass = ((obj == null || !Modifier.isProtected(modifiers))
  543. ? clazz
  544. : obj.getClass());
  545. if (securityCheckCache != caller ||
  546. targetClass != securityCheckTargetClassCache) {
  547. Reflection.ensureMemberAccess(caller, clazz, obj, modifiers);
  548. securityCheckCache = caller;
  549. securityCheckTargetClassCache = targetClass;
  550. }
  551. }
  552. }
  553. if (methodAccessor == null) acquireMethodAccessor();
  554. return methodAccessor.invoke(obj, args);
  555. }
  556. /**
  557. * Returns <tt>true</tt> if this method is a bridge
  558. * method; returns <tt>false</tt> otherwise.
  559. *
  560. * @return true if and only if this method is a bridge
  561. * method as defined by the Java Language Specification.
  562. * @since 1.5
  563. */
  564. public boolean isBridge() {
  565. return (getModifiers() & Modifier.BRIDGE) != 0;
  566. }
  567. /**
  568. * Returns <tt>true</tt> if this method was declared to take
  569. * a variable number of arguments; returns <tt>false</tt>
  570. * otherwise.
  571. *
  572. * @return <tt>true</tt> if an only if this method was declared to
  573. * take a variable number of arguments.
  574. * @since 1.5
  575. */
  576. public boolean isVarArgs() {
  577. return (getModifiers() & Modifier.VARARGS) != 0;
  578. }
  579. /**
  580. * Returns <tt>true</tt> if this method is a synthetic
  581. * method; returns <tt>false</tt> otherwise.
  582. *
  583. * @return true if and only if this method is a synthetic
  584. * method as defined by the Java Language Specification.
  585. * @since 1.5
  586. */
  587. public boolean isSynthetic() {
  588. return Modifier.isSynthetic(getModifiers());
  589. }
  590. // NOTE that there is no synchronization used here. It is correct
  591. // (though not efficient) to generate more than one MethodAccessor
  592. // for a given Method. However, avoiding synchronization will
  593. // probably make the implementation more scalable.
  594. private void acquireMethodAccessor() {
  595. // First check to see if one has been created yet, and take it
  596. // if so
  597. MethodAccessor tmp = null;
  598. if (root != null) tmp = root.getMethodAccessor();
  599. if (tmp != null) {
  600. methodAccessor = tmp;
  601. return;
  602. }
  603. // Otherwise fabricate one and propagate it up to the root
  604. tmp = reflectionFactory.newMethodAccessor(this);
  605. setMethodAccessor(tmp);
  606. }
  607. // Returns MethodAccessor for this Method object, not looking up
  608. // the chain to the root
  609. MethodAccessor getMethodAccessor() {
  610. return methodAccessor;
  611. }
  612. // Sets the MethodAccessor for this Method object and
  613. // (recursively) its root
  614. void setMethodAccessor(MethodAccessor accessor) {
  615. methodAccessor = accessor;
  616. // Propagate up
  617. if (root != null) {
  618. root.setMethodAccessor(accessor);
  619. }
  620. }
  621. public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
  622. if (annotationClass == null)
  623. throw new NullPointerException();
  624. return (T) declaredAnnotations().get(annotationClass);
  625. }
  626. private static final Annotation[] EMPTY_ANNOTATION_ARRAY=new Annotation[0];
  627. public Annotation[] getDeclaredAnnotations() {
  628. return declaredAnnotations().values().toArray(EMPTY_ANNOTATION_ARRAY);
  629. }
  630. private transient Map<Class, Annotation> declaredAnnotations;
  631. private synchronized Map<Class, Annotation> declaredAnnotations() {
  632. if (declaredAnnotations == null) {
  633. declaredAnnotations = AnnotationParser.parseAnnotations(
  634. annotations, sun.misc.SharedSecrets.getJavaLangAccess().
  635. getConstantPool(getDeclaringClass()),
  636. getDeclaringClass());
  637. }
  638. return declaredAnnotations;
  639. }
  640. /**
  641. * Returns the default value for the annotation member represented by
  642. * this <tt>Method</tt> instance. If the member is of a primitive type,
  643. * an instance of the corresponding wrapper type is returned. Returns
  644. * null if no default is associated with the member, or if the method
  645. * instance does not represent a declared member of an annotation type.
  646. *
  647. * @return the default value for the annotation member represented
  648. * by this <tt>Method</tt> instance.
  649. * @throws TypeNotPresentException if the annotation is of type
  650. * {@link Class} and no definition can be found for the
  651. * default class value.
  652. * @since 1.5
  653. */
  654. public Object getDefaultValue() {
  655. if (annotationDefault == null)
  656. return null;
  657. Class memberType = AnnotationType.invocationHandlerReturnType(
  658. getReturnType());
  659. Object result = AnnotationParser.parseMemberValue(
  660. memberType, ByteBuffer.wrap(annotationDefault),
  661. sun.misc.SharedSecrets.getJavaLangAccess().
  662. getConstantPool(getDeclaringClass()),
  663. getDeclaringClass());
  664. if (result instanceof sun.reflect.annotation.ExceptionProxy)
  665. throw new AnnotationFormatError("Invalid default: " + this);
  666. return result;
  667. }
  668. /**
  669. * Returns an array of arrays that represent the annotations on the formal
  670. * parameters, in declaration order, of the method represented by
  671. * this <tt>Method</tt> object. (Returns an array of length zero if the
  672. * underlying method is parameterless. If the method has one or more
  673. * parameters, a nested array of length zero is returned for each parameter
  674. * with no annotations.) The annotation objects contained in the returned
  675. * arrays are serializable. The caller of this method is free to modify
  676. * the returned arrays; it will have no effect on the arrays returned to
  677. * other callers.
  678. *
  679. * @return an array of arrays that represent the annotations on the formal
  680. * parameters, in declaration order, of the method represented by this
  681. * Method object
  682. * @since 1.5
  683. */
  684. public Annotation[][] getParameterAnnotations() {
  685. int numParameters = parameterTypes.length;
  686. if (parameterAnnotations == null)
  687. return new Annotation[numParameters][0];
  688. Annotation[][] result = AnnotationParser.parseParameterAnnotations(
  689. parameterAnnotations,
  690. sun.misc.SharedSecrets.getJavaLangAccess().
  691. getConstantPool(getDeclaringClass()),
  692. getDeclaringClass());
  693. if (result.length != numParameters)
  694. throw new java.lang.annotation.AnnotationFormatError(
  695. "Parameter annotations don't match number of parameters");
  696. return result;
  697. }
  698. }