KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > java > lang > reflect > Method


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
8 package java.lang.reflect;
9
10 import sun.reflect.MethodAccessor;
11 import sun.reflect.Reflection;
12 import sun.reflect.generics.repository.MethodRepository;
13 import sun.reflect.generics.factory.CoreReflectionFactory;
14 import sun.reflect.generics.factory.GenericsFactory;
15 import sun.reflect.generics.scope.MethodScope;
16 import sun.reflect.annotation.AnnotationType;
17 import sun.reflect.annotation.AnnotationParser;
18 import java.lang.annotation.Annotation JavaDoc;
19 import java.lang.annotation.AnnotationFormatError JavaDoc;
20 import java.nio.ByteBuffer JavaDoc;
21 import java.util.Map JavaDoc;
22
23 /**
24  * A <code>Method</code> provides information about, and access to, a single method
25  * on a class or interface. The reflected method may be a class method
26  * or an instance method (including an abstract method).
27  *
28  * <p>A <code>Method</code> permits widening conversions to occur when matching the
29  * actual parameters to invoke with the underlying method's formal
30  * parameters, but it throws an <code>IllegalArgumentException</code> if a
31  * narrowing conversion would occur.
32  *
33  * @see Member
34  * @see java.lang.Class
35  * @see java.lang.Class#getMethods()
36  * @see java.lang.Class#getMethod(String, Class[])
37  * @see java.lang.Class#getDeclaredMethods()
38  * @see java.lang.Class#getDeclaredMethod(String, Class[])
39  *
40  * @author Kenneth Russell
41  * @author Nakul Saraiya
42  */

43 public final
44     class Method extends AccessibleObject JavaDoc implements GenericDeclaration JavaDoc,
45                              Member JavaDoc {
46
47
48     private Class JavaDoc clazz;
49     private int slot;
50     // This is guaranteed to be interned by the VM in the 1.4
51
// reflection implementation
52
private String JavaDoc name;
53     private Class JavaDoc returnType;
54     private Class JavaDoc[] parameterTypes;
55     private Class JavaDoc[] exceptionTypes;
56     private int modifiers;
57     // Generics and annotations support
58
private transient String JavaDoc signature;
59     // generic info repository; lazily initialized
60
private transient MethodRepository genericInfo;
61     private byte[] annotations;
62     private byte[] parameterAnnotations;
63     private byte[] annotationDefault;
64     private volatile MethodAccessor methodAccessor;
65     // For sharing of MethodAccessors. This branching structure is
66
// currently only two levels deep (i.e., one root Method and
67
// potentially many Method objects pointing to it.)
68
private Method JavaDoc root;
69
70     // More complicated security check cache needed here than for
71
// Class.newInstance() and Constructor.newInstance()
72
private volatile Class JavaDoc securityCheckTargetClassCache;
73
74     // Generics infrastructure
75

76     private String JavaDoc getGenericSignature() {return signature;}
77
78     // Accessor for factory
79
private GenericsFactory getFactory() {
80     // create scope and factory
81
return CoreReflectionFactory.make(this, MethodScope.make(this));
82     }
83
84     // Accessor for generic info repository
85
private MethodRepository getGenericInfo() {
86     // lazily initialize repository if necessary
87
if (genericInfo == null) {
88         // create and cache generic info repository
89
genericInfo = MethodRepository.make(getGenericSignature(),
90                         getFactory());
91     }
92     return genericInfo; //return cached repository
93
}
94
95     /**
96      * Package-private constructor used by ReflectAccess to enable
97      * instantiation of these objects in Java code from the java.lang
98      * package via sun.reflect.LangReflectAccess.
99      */

100     Method(Class JavaDoc declaringClass,
101            String JavaDoc name,
102            Class JavaDoc[] parameterTypes,
103            Class JavaDoc returnType,
104            Class JavaDoc[] checkedExceptions,
105            int modifiers,
106            int slot,
107            String JavaDoc signature,
108            byte[] annotations,
109            byte[] parameterAnnotations,
110            byte[] annotationDefault)
111     {
112         this.clazz = declaringClass;
113         this.name = name;
114         this.parameterTypes = parameterTypes;
115         this.returnType = returnType;
116         this.exceptionTypes = checkedExceptions;
117         this.modifiers = modifiers;
118         this.slot = slot;
119         this.signature = signature;
120         this.annotations = annotations;
121         this.parameterAnnotations = parameterAnnotations;
122         this.annotationDefault = annotationDefault;
123     }
124
125     /**
126      * Package-private routine (exposed to java.lang.Class via
127      * ReflectAccess) which returns a copy of this Method. The copy's
128      * "root" field points to this Method.
129      */

130     Method JavaDoc copy() {
131         // This routine enables sharing of MethodAccessor objects
132
// among Method objects which refer to the same underlying
133
// method in the VM. (All of this contortion is only necessary
134
// because of the "accessibility" bit in AccessibleObject,
135
// which implicitly requires that new java.lang.reflect
136
// objects be fabricated for each reflective call on Class
137
// objects.)
138
Method JavaDoc res = new Method JavaDoc(clazz, name, parameterTypes, returnType,
139                                 exceptionTypes, modifiers, slot, signature,
140                                 annotations, parameterAnnotations, annotationDefault);
141         res.root = this;
142         // Might as well eagerly propagate this if already present
143
res.methodAccessor = methodAccessor;
144         return res;
145     }
146
147     /**
148      * Returns the <code>Class</code> object representing the class or interface
149      * that declares the method represented by this <code>Method</code> object.
150      */

151     public Class JavaDoc<?> getDeclaringClass() {
152     return clazz;
153     }
154
155     /**
156      * Returns the name of the method represented by this <code>Method</code>
157      * object, as a <code>String</code>.
158      */

159     public String JavaDoc getName() {
160     return name;
161     }
162
163     /**
164      * Returns the Java language modifiers for the method represented
165      * by this <code>Method</code> object, as an integer. The <code>Modifier</code> class should
166      * be used to decode the modifiers.
167      *
168      * @see Modifier
169      */

170     public int getModifiers() {
171     return modifiers;
172     }
173
174     /**
175      * Returns an array of <tt>TypeVariable</tt> objects that represent the
176      * type variables declared by the generic declaration represented by this
177      * <tt>GenericDeclaration</tt> object, in declaration order. Returns an
178      * array of length 0 if the underlying generic declaration declares no type
179      * variables.
180      *
181      * @return an array of <tt>TypeVariable</tt> objects that represent
182      * the type variables declared by this generic declaration
183      * @throws GenericSignatureFormatError if the generic
184      * signature of this generic declaration does not conform to
185      * the format specified in the Java Virtual Machine Specification,
186      * 3rd edition
187      * @since 1.5
188      */

189     public TypeVariable JavaDoc<Method JavaDoc>[] getTypeParameters() {
190     if (getGenericSignature() != null)
191         return (TypeVariable JavaDoc<Method JavaDoc>[])getGenericInfo().getTypeParameters();
192     else
193         return (TypeVariable JavaDoc<Method JavaDoc>[])new TypeVariable JavaDoc[0];
194     }
195
196     /**
197      * Returns a <code>Class</code> object that represents the formal return type
198      * of the method represented by this <code>Method</code> object.
199      *
200      * @return the return type for the method this object represents
201      */

202     public Class JavaDoc<?> getReturnType() {
203     return returnType;
204     }
205
206     /**
207      * Returns a <tt>Type</tt> object that represents the formal return
208      * type of the method represented by this <tt>Method</tt> object.
209      *
210      * <p>If the return type is a parameterized type,
211      * the <tt>Type</tt> object returned must accurately reflect
212      * the actual type parameters used in the source code.
213      *
214      * <p>If the return type is a type variable or a parameterized type, it
215      * is created. Otherwise, it is resolved.
216      *
217      * @return a <tt>Type</tt> object that represents the formal return
218      * type of the underlying method
219      * @throws GenericSignatureFormatError
220      * if the generic method signature does not conform to the format
221      * specified in the Java Virtual Machine Specification, 3rd edition
222      * @throws TypeNotPresentException if the underlying method's
223      * return type refers to a non-existent type declaration
224      * @throws MalformedParameterizedTypeException if the
225      * underlying method's return typed refers to a parameterized
226      * type that cannot be instantiated for any reason
227      * @since 1.5
228      */

229     public Type JavaDoc getGenericReturnType() {
230       if (getGenericSignature() != null) {
231     return getGenericInfo().getReturnType();
232       } else { return getReturnType();}
233     }
234
235
236     /**
237      * Returns an array of <code>Class</code> objects that represent the formal
238      * parameter types, in declaration order, of the method
239      * represented by this <code>Method</code> object. Returns an array of length
240      * 0 if the underlying method takes no parameters.
241      *
242      * @return the parameter types for the method this object
243      * represents
244      */

245     public Class JavaDoc<?>[] getParameterTypes() {
246     return (Class JavaDoc<?>[]) parameterTypes.clone();
247     }
248
249     /**
250      * Returns an array of <tt>Type</tt> objects that represent the formal
251      * parameter types, in declaration order, of the method represented by
252      * this <tt>Method</tt> object. Returns an array of length 0 if the
253      * underlying method takes no parameters.
254      *
255      * <p>If a formal parameter type is a parameterized type,
256      * the <tt>Type</tt> object returned for it must accurately reflect
257      * the actual type parameters used in the source code.
258      *
259      * <p>If a formal parameter type is a type variable or a parameterized
260      * type, it is created. Otherwise, it is resolved.
261      *
262      * @return an array of Types that represent the formal
263      * parameter types of the underlying method, in declaration order
264      * @throws GenericSignatureFormatError
265      * if the generic method signature does not conform to the format
266      * specified in the Java Virtual Machine Specification, 3rd edition
267      * @throws TypeNotPresentException if any of the parameter
268      * types of the underlying method refers to a non-existent type
269      * declaration
270      * @throws MalformedParameterizedTypeException if any of
271      * the underlying method's parameter types refer to a parameterized
272      * type that cannot be instantiated for any reason
273      * @since 1.5
274      */

275     public Type JavaDoc[] getGenericParameterTypes() {
276     if (getGenericSignature() != null)
277         return getGenericInfo().getParameterTypes();
278     else
279         return getParameterTypes();
280     }
281
282
283     /**
284      * Returns an array of <code>Class</code> objects that represent
285      * the types of the exceptions declared to be thrown
286      * by the underlying method
287      * represented by this <code>Method</code> object. Returns an array of length
288      * 0 if the method declares no exceptions in its <code>throws</code> clause.
289      *
290      * @return the exception types declared as being thrown by the
291      * method this object represents
292      */

293     public Class JavaDoc<?>[] getExceptionTypes() {
294     return (Class JavaDoc<?>[]) exceptionTypes.clone();
295     }
296
297     /**
298      * Returns an array of <tt>Type</tt> objects that represent the
299      * exceptions declared to be thrown by this <tt>Method</tt> object.
300      * Returns an array of length 0 if the underlying method declares
301      * no exceptions in its <tt>throws</tt> clause.
302      *
303      * <p>If an exception type is a parameterized type, the <tt>Type</tt>
304      * object returned for it must accurately reflect the actual type
305      * parameters used in the source code.
306      *
307      * <p>If an exception type is a type variable or a parameterized
308      * type, it is created. Otherwise, it is resolved.
309      *
310      * @return an array of Types that represent the exception types
311      * thrown by the underlying method
312      * @throws GenericSignatureFormatError
313      * if the generic method signature does not conform to the format
314      * specified in the Java Virtual Machine Specification, 3rd edition
315      * @throws TypeNotPresentException if the underlying method's
316      * <tt>throws</tt> clause refers to a non-existent type declaration
317      * @throws MalformedParameterizedTypeException if
318      * the underlying method's <tt>throws</tt> clause refers to a
319      * parameterized type that cannot be instantiated for any reason
320      * @since 1.5
321      */

322       public Type JavaDoc[] getGenericExceptionTypes() {
323       Type JavaDoc[] result;
324       if (getGenericSignature() != null &&
325           ((result = getGenericInfo().getExceptionTypes()).length > 0))
326           return result;
327       else
328           return getExceptionTypes();
329       }
330
331     /**
332      * Compares this <code>Method</code> against the specified object. Returns
333      * true if the objects are the same. Two <code>Methods</code> are the same if
334      * they were declared by the same class and have the same name
335      * and formal parameter types and return type.
336      */

337     public boolean equals(Object JavaDoc obj) {
338     if (obj != null && obj instanceof Method JavaDoc) {
339         Method JavaDoc other = (Method JavaDoc)obj;
340         if ((getDeclaringClass() == other.getDeclaringClass())
341         && (getName() == other.getName())) {
342         if (!returnType.equals(other.getReturnType()))
343             return false;
344         /* Avoid unnecessary cloning */
345         Class JavaDoc[] params1 = parameterTypes;
346         Class JavaDoc[] params2 = other.parameterTypes;
347         if (params1.length == params2.length) {
348             for (int i = 0; i < params1.length; i++) {
349             if (params1[i] != params2[i])
350                 return false;
351             }
352             return true;
353         }
354         }
355     }
356     return false;
357     }
358
359     /**
360      * Returns a hashcode for this <code>Method</code>. The hashcode is computed
361      * as the exclusive-or of the hashcodes for the underlying
362      * method's declaring class name and the method's name.
363      */

364     public int hashCode() {
365     return getDeclaringClass().getName().hashCode() ^ getName().hashCode();
366     }
367
368     /**
369      * Returns a string describing this <code>Method</code>. The string is
370      * formatted as the method access modifiers, if any, followed by
371      * the method return type, followed by a space, followed by the
372      * class declaring the method, followed by a period, followed by
373      * the method name, followed by a parenthesized, comma-separated
374      * list of the method's formal parameter types. If the method
375      * throws checked exceptions, the parameter list is followed by a
376      * space, followed by the word throws followed by a
377      * comma-separated list of the thrown exception types.
378      * For example:
379      * <pre>
380      * public boolean java.lang.Object.equals(java.lang.Object)
381      * </pre>
382      *
383      * <p>The access modifiers are placed in canonical order as
384      * specified by "The Java Language Specification". This is
385      * <tt>public</tt>, <tt>protected</tt> or <tt>private</tt> first,
386      * and then other modifiers in the following order:
387      * <tt>abstract</tt>, <tt>static</tt>, <tt>final</tt>,
388      * <tt>synchronized</tt> <tt>native</tt>.
389      */

390     public String JavaDoc toString() {
391     try {
392         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
393         int mod = getModifiers();
394         if (mod != 0) {
395         sb.append(Modifier.toString(mod) + " ");
396         }
397         sb.append(Field.getTypeName(getReturnType()) + " ");
398         sb.append(Field.getTypeName(getDeclaringClass()) + ".");
399         sb.append(getName() + "(");
400         Class JavaDoc[] params = parameterTypes; // avoid clone
401
for (int j = 0; j < params.length; j++) {
402         sb.append(Field.getTypeName(params[j]));
403         if (j < (params.length - 1))
404             sb.append(",");
405         }
406         sb.append(")");
407         Class JavaDoc[] exceptions = exceptionTypes; // avoid clone
408
if (exceptions.length > 0) {
409         sb.append(" throws ");
410         for (int k = 0; k < exceptions.length; k++) {
411             sb.append(exceptions[k].getName());
412             if (k < (exceptions.length - 1))
413             sb.append(",");
414         }
415         }
416         return sb.toString();
417     } catch (Exception JavaDoc e) {
418         return "<" + e + ">";
419     }
420     }
421
422     /**
423      * Returns a string describing this <code>Method</code>, including
424      * type parameters. The string is formatted as the method access
425      * modifiers, if any, followed by an angle-bracketed
426      * comma-separated list of the method's type parameters, if any,
427      * followed by the method's generic return type, followed by a
428      * space, followed by the class declaring the method, followed by
429      * a period, followed by the method name, followed by a
430      * parenthesized, comma-separated list of the method's generic
431      * formal parameter types. A space is used to separate access
432      * modifiers from one another and from the type parameters or
433      * return type. If there are no type parameters, the type
434      * parameter list is elided; if the type parameter list is
435      * present, a space separates the list from the class name. If
436      * the method is declared to throw exceptions, the parameter list
437      * is followed by a space, followed by the word throws followed by
438      * a comma-separated list of the generic thrown exception types.
439      * If there are no type parameters, the type parameter list is
440      * elided.
441      *
442      * <p>The access modifiers are placed in canonical order as
443      * specified by "The Java Language Specification". This is
444      * <tt>public</tt>, <tt>protected</tt> or <tt>private</tt> first,
445      * and then other modifiers in the following order:
446      * <tt>abstract</tt>, <tt>static</tt>, <tt>final</tt>,
447      * <tt>synchronized</tt> <tt>native</tt>.
448      *
449      * @return a string describing this <code>Method</code>,
450      * include type parameters
451      *
452      * @since 1.5
453      */

454     public String JavaDoc toGenericString() {
455     try {
456         StringBuilder JavaDoc sb = new StringBuilder JavaDoc();
457         int mod = getModifiers();
458         if (mod != 0) {
459         sb.append(Modifier.toString(mod) + " ");
460         }
461         Type JavaDoc[] typeparms = getTypeParameters();
462         if (typeparms.length > 0) {
463         boolean first = true;
464         sb.append("<");
465         for(Type JavaDoc typeparm: typeparms) {
466             if (!first)
467             sb.append(",");
468             if (typeparm instanceof Class JavaDoc)
469             sb.append(((Class JavaDoc)typeparm).getName());
470             else
471             sb.append(typeparm.toString());
472             first = false;
473         }
474         sb.append("> ");
475         }
476
477         Type JavaDoc genRetType = getGenericReturnType();
478         sb.append( ((genRetType instanceof Class JavaDoc)?
479             Field.getTypeName((Class JavaDoc)genRetType):genRetType.toString()) + " ");
480
481         sb.append(Field.getTypeName(getDeclaringClass()) + ".");
482         sb.append(getName() + "(");
483         Type JavaDoc[] params = getGenericParameterTypes();
484         for (int j = 0; j < params.length; j++) {
485         sb.append((params[j] instanceof Class JavaDoc)?
486               Field.getTypeName((Class JavaDoc)params[j]):
487               (params[j].toString()) );
488         if (j < (params.length - 1))
489             sb.append(",");
490         }
491         sb.append(")");
492         Type JavaDoc[] exceptions = getGenericExceptionTypes();
493         if (exceptions.length > 0) {
494         sb.append(" throws ");
495         for (int k = 0; k < exceptions.length; k++) {
496             sb.append((exceptions[k] instanceof Class JavaDoc)?
497                   ((Class JavaDoc)exceptions[k]).getName():
498                   exceptions[k].toString());
499             if (k < (exceptions.length - 1))
500             sb.append(",");
501         }
502         }
503         return sb.toString();
504     } catch (Exception JavaDoc e) {
505         return "<" + e + ">";
506     }
507     }
508
509     /**
510      * Invokes the underlying method represented by this <code>Method</code>
511      * object, on the specified object with the specified parameters.
512      * Individual parameters are automatically unwrapped to match
513      * primitive formal parameters, and both primitive and reference
514      * parameters are subject to method invocation conversions as
515      * necessary.
516      *
517      * <p>If the underlying method is static, then the specified <code>obj</code>
518      * argument is ignored. It may be null.
519      *
520      * <p>If the number of formal parameters required by the underlying method is
521      * 0, the supplied <code>args</code> array may be of length 0 or null.
522      *
523      * <p>If the underlying method is an instance method, it is invoked
524      * using dynamic method lookup as documented in The Java Language
525      * Specification, Second Edition, section 15.12.4.4; in particular,
526      * overriding based on the runtime type of the target object will occur.
527      *
528      * <p>If the underlying method is static, the class that declared
529      * the method is initialized if it has not already been initialized.
530      *
531      * <p>If the method completes normally, the value it returns is
532      * returned to the caller of invoke; if the value has a primitive
533      * type, it is first appropriately wrapped in an object. However,
534      * if the value has the type of an array of a primitive type, the
535      * elements of the array are <i>not</i> wrapped in objects; in
536      * other words, an array of primitive type is returned. If the
537      * underlying method return type is void, the invocation returns
538      * null.
539      *
540      * @param obj the object the underlying method is invoked from
541      * @param args the arguments used for the method call
542      * @return the result of dispatching the method represented by
543      * this object on <code>obj</code> with parameters
544      * <code>args</code>
545      *
546      * @exception IllegalAccessException if this <code>Method</code> object
547      * enforces Java language access control and the underlying
548      * method is inaccessible.
549      * @exception IllegalArgumentException if the method is an
550      * instance method and the specified object argument
551      * is not an instance of the class or interface
552      * declaring the underlying method (or of a subclass
553      * or implementor thereof); if the number of actual
554      * and formal parameters differ; if an unwrapping
555      * conversion for primitive arguments fails; or if,
556      * after possible unwrapping, a parameter value
557      * cannot be converted to the corresponding formal
558      * parameter type by a method invocation conversion.
559      * @exception InvocationTargetException if the underlying method
560      * throws an exception.
561      * @exception NullPointerException if the specified object is null
562      * and the method is an instance method.
563      * @exception ExceptionInInitializerError if the initialization
564      * provoked by this method fails.
565      */

566     public Object JavaDoc invoke(Object JavaDoc obj, Object JavaDoc... args)
567     throws IllegalAccessException JavaDoc, IllegalArgumentException JavaDoc,
568            InvocationTargetException JavaDoc
569     {
570         if (!override) {
571             if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
572                 Class JavaDoc caller = Reflection.getCallerClass(1);
573                 Class JavaDoc targetClass = ((obj == null || !Modifier.isProtected(modifiers))
574                                      ? clazz
575                                      : obj.getClass());
576                 if (securityCheckCache != caller ||
577                     targetClass != securityCheckTargetClassCache) {
578                     Reflection.ensureMemberAccess(caller, clazz, obj, modifiers);
579                     securityCheckCache = caller;
580                     securityCheckTargetClassCache = targetClass;
581                 }
582             }
583         }
584         if (methodAccessor == null) acquireMethodAccessor();
585         return methodAccessor.invoke(obj, args);
586     }
587
588     /**
589      * Returns <tt>true</tt> if this method is a bridge
590      * method; returns <tt>false</tt> otherwise.
591      *
592      * @return true if and only if this method is a bridge
593      * method as defined by the Java Language Specification.
594      * @since 1.5
595      */

596     public boolean isBridge() {
597         return (getModifiers() & Modifier.BRIDGE) != 0;
598     }
599
600     /**
601      * Returns <tt>true</tt> if this method was declared to take
602      * a variable number of arguments; returns <tt>false</tt>
603      * otherwise.
604      *
605      * @return <tt>true</tt> if an only if this method was declared to
606      * take a variable number of arguments.
607      * @since 1.5
608      */

609     public boolean isVarArgs() {
610         return (getModifiers() & Modifier.VARARGS) != 0;
611     }
612
613     /**
614      * Returns <tt>true</tt> if this method is a synthetic
615      * method; returns <tt>false</tt> otherwise.
616      *
617      * @return true if and only if this method is a synthetic
618      * method as defined by the Java Language Specification.
619      * @since 1.5
620      */

621     public boolean isSynthetic() {
622         return Modifier.isSynthetic(getModifiers());
623     }
624
625     // NOTE that there is no synchronization used here. It is correct
626
// (though not efficient) to generate more than one MethodAccessor
627
// for a given Method. However, avoiding synchronization will
628
// probably make the implementation more scalable.
629
private void acquireMethodAccessor() {
630         // First check to see if one has been created yet, and take it
631
// if so
632
MethodAccessor tmp = null;
633         if (root != null) tmp = root.getMethodAccessor();
634         if (tmp != null) {
635             methodAccessor = tmp;
636             return;
637         }
638         // Otherwise fabricate one and propagate it up to the root
639
tmp = reflectionFactory.newMethodAccessor(this);
640         setMethodAccessor(tmp);
641     }
642
643     // Returns MethodAccessor for this Method object, not looking up
644
// the chain to the root
645
MethodAccessor getMethodAccessor() {
646         return methodAccessor;
647     }
648
649     // Sets the MethodAccessor for this Method object and
650
// (recursively) its root
651
void setMethodAccessor(MethodAccessor accessor) {
652         methodAccessor = accessor;
653         // Propagate up
654
if (root != null) {
655             root.setMethodAccessor(accessor);
656         }
657     }
658
659     public <T extends Annotation JavaDoc> T getAnnotation(Class JavaDoc<T> annotationClass) {
660         if (annotationClass == null)
661             throw new NullPointerException JavaDoc();
662
663         return (T) declaredAnnotations().get(annotationClass);
664     }
665
666     private static final Annotation JavaDoc[] EMPTY_ANNOTATION_ARRAY=new Annotation JavaDoc[0];
667
668     public Annotation JavaDoc[] getDeclaredAnnotations() {
669         return declaredAnnotations().values().toArray(EMPTY_ANNOTATION_ARRAY);
670     }
671
672     private transient Map JavaDoc<Class JavaDoc, Annotation JavaDoc> declaredAnnotations;
673
674     private synchronized Map JavaDoc<Class JavaDoc, Annotation JavaDoc> declaredAnnotations() {
675         if (declaredAnnotations == null) {
676             declaredAnnotations = AnnotationParser.parseAnnotations(
677                 annotations, sun.misc.SharedSecrets.getJavaLangAccess().
678                 getConstantPool(getDeclaringClass()),
679                 getDeclaringClass());
680         }
681         return declaredAnnotations;
682     }
683
684     /**
685      * Returns the default value for the annotation member represented by
686      * this <tt>Method</tt> instance. If the member is of a primitive type,
687      * an instance of the corresponding wrapper type is returned. Returns
688      * null if no default is associated with the member, or if the method
689      * instance does not represent a declared member of an annotation type.
690      *
691      * @return the default value for the annotation member represented
692      * by this <tt>Method</tt> instance.
693      * @throws TypeNotPresentException if the annotation is of type
694      * {@link Class} and no definition can be found for the
695      * default class value.
696      * @since 1.5
697      */

698     public Object JavaDoc getDefaultValue() {
699         if (annotationDefault == null)
700             return null;
701         Class JavaDoc memberType = AnnotationType.invocationHandlerReturnType(
702             getReturnType());
703         Object JavaDoc result = AnnotationParser.parseMemberValue(
704             memberType, ByteBuffer.wrap(annotationDefault),
705             sun.misc.SharedSecrets.getJavaLangAccess().
706                 getConstantPool(getDeclaringClass()),
707             getDeclaringClass());
708         if (result instanceof sun.reflect.annotation.ExceptionProxy)
709             throw new AnnotationFormatError JavaDoc("Invalid default: " + this);
710         return result;
711     }
712
713     /**
714      * Returns an array of arrays that represent the annotations on the formal
715      * parameters, in declaration order, of the method represented by
716      * this <tt>Method</tt> object. (Returns an array of length zero if the
717      * underlying method is parameterless. If the method has one or more
718      * parameters, a nested array of length zero is returned for each parameter
719      * with no annotations.) The annotation objects contained in the returned
720      * arrays are serializable. The caller of this method is free to modify
721      * the returned arrays; it will have no effect on the arrays returned to
722      * other callers.
723      *
724      * @return an array of arrays that represent the annotations on the formal
725      * parameters, in declaration order, of the method represented by this
726      * Method object
727      * @since 1.5
728      */

729     public Annotation JavaDoc[][] getParameterAnnotations() {
730         int numParameters = parameterTypes.length;
731         if (parameterAnnotations == null)
732             return new Annotation JavaDoc[numParameters][0];
733
734         Annotation JavaDoc[][] result = AnnotationParser.parseParameterAnnotations(
735             parameterAnnotations,
736             sun.misc.SharedSecrets.getJavaLangAccess().
737                 getConstantPool(getDeclaringClass()),
738             getDeclaringClass());
739         if (result.length != numParameters)
740             throw new java.lang.annotation.AnnotationFormatError JavaDoc(
741                 "Parameter annotations don't match number of parameters");
742         return result;
743     }
744 }
745
Popular Tags