1 /*
  2  * Copyright (c) 2012, 2023, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.  Oracle designates this
  8  * particular file as subject to the "Classpath" exception as provided
  9  * by Oracle in the LICENSE file that accompanied this code.
 10  *
 11  * This code is distributed in the hope that it will be useful, but WITHOUT
 12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 14  * version 2 for more details (a copy is included in the LICENSE file that
 15  * accompanied this code).
 16  *
 17  * You should have received a copy of the GNU General Public License version
 18  * 2 along with this work; if not, write to the Free Software Foundation,
 19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 20  *
 21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 22  * or visit www.oracle.com if you need additional information or have any
 23  * questions.
 24  */
 25 
 26 package java.lang.reflect;
 27 
 28 import java.lang.annotation.Annotation;
 29 import java.util.Arrays;
 30 import java.util.Map;
 31 import java.util.Set;
 32 import java.util.Objects;
 33 import java.util.StringJoiner;
 34 import java.util.stream.Collectors;
 35 
 36 import jdk.internal.access.SharedSecrets;
 37 import jdk.internal.vm.annotation.Stable;
 38 import sun.reflect.annotation.AnnotationParser;
 39 import sun.reflect.annotation.AnnotationSupport;
 40 import sun.reflect.annotation.TypeAnnotationParser;
 41 import sun.reflect.annotation.TypeAnnotation;
 42 import sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl;
 43 import sun.reflect.generics.repository.ConstructorRepository;
 44 
 45 /**
 46  * A shared superclass for the common functionality of {@link Method}
 47  * and {@link Constructor}.
 48  *
 49  * @sealedGraph
 50  * @since 1.8
 51  */
 52 public abstract sealed class Executable extends AccessibleObject
 53     implements Member, GenericDeclaration permits Constructor, Method {
 54     /*
 55      * Only grant package-visibility to the constructor.
 56      */
 57     @SuppressWarnings("deprecation")
 58     Executable() {}
 59 
 60     /**
 61      * Accessor method to allow code sharing
 62      */
 63     abstract byte[] getAnnotationBytes();
 64 
 65     /**
 66      * Does the Executable have generic information.
 67      */
 68     abstract boolean hasGenericInformation();
 69 
 70     abstract ConstructorRepository getGenericInfo();
 71 
 72     boolean equalParamTypes(Class<?>[] params1, Class<?>[] params2) {
 73         /* Avoid unnecessary cloning */
 74         if (params1.length == params2.length) {
 75             for (int i = 0; i < params1.length; i++) {
 76                 if (params1[i] != params2[i])
 77                     return false;
 78             }
 79             return true;
 80         }
 81         return false;
 82     }
 83 
 84     Annotation[][] parseParameterAnnotations(byte[] parameterAnnotations) {
 85         return AnnotationParser.parseParameterAnnotations(
 86                parameterAnnotations,
 87                SharedSecrets.getJavaLangAccess().
 88                getConstantPool(getDeclaringClass()),
 89                getDeclaringClass());
 90     }
 91 
 92     void printModifiersIfNonzero(StringBuilder sb, int mask, boolean isDefault) {
 93         int mod = getModifiers() & mask;
 94 
 95         if (mod != 0 && !isDefault) {
 96             sb.append(Modifier.toString(mod)).append(' ');
 97         } else {
 98             int access_mod = mod & Modifier.ACCESS_MODIFIERS;
 99             if (access_mod != 0)
100                 sb.append(Modifier.toString(access_mod)).append(' ');
101             if (isDefault)
102                 sb.append("default ");
103             mod = (mod & ~Modifier.ACCESS_MODIFIERS);
104             if (mod != 0)
105                 sb.append(Modifier.toString(mod)).append(' ');
106         }
107     }
108 
109     String sharedToString(int modifierMask,
110                           boolean isDefault,
111                           Class<?>[] parameterTypes,
112                           Class<?>[] exceptionTypes) {
113         try {
114             StringBuilder sb = new StringBuilder();
115 
116             printModifiersIfNonzero(sb, modifierMask, isDefault);
117             specificToStringHeader(sb);
118             sb.append(Arrays.stream(parameterTypes)
119                       .map(Type::getTypeName)
120                       .collect(Collectors.joining(",", "(", ")")));
121             if (exceptionTypes.length > 0) {
122                 sb.append(Arrays.stream(exceptionTypes)
123                           .map(Type::getTypeName)
124                           .collect(Collectors.joining(",", " throws ", "")));
125             }
126             return sb.toString();
127         } catch (Exception e) {
128             return "<" + e + ">";
129         }
130     }
131 
132     /**
133      * Generate toString header information specific to a method or
134      * constructor.
135      */
136     abstract void specificToStringHeader(StringBuilder sb);
137 
138     static String typeVarBounds(TypeVariable<?> typeVar) {
139         Type[] bounds = typeVar.getBounds();
140         if (bounds.length == 1 && bounds[0].equals(Object.class)) {
141             return typeVar.getName();
142         } else {
143             return typeVar.getName() + " extends " +
144                 Arrays.stream(bounds)
145                 .map(Type::getTypeName)
146                 .collect(Collectors.joining(" & "));
147         }
148     }
149 
150     String sharedToGenericString(int modifierMask, boolean isDefault) {
151         try {
152             StringBuilder sb = new StringBuilder();
153 
154             printModifiersIfNonzero(sb, modifierMask, isDefault);
155 
156             TypeVariable<?>[] typeparms = getTypeParameters();
157             if (typeparms.length > 0) {
158                 sb.append(Arrays.stream(typeparms)
159                           .map(Executable::typeVarBounds)
160                           .collect(Collectors.joining(",", "<", "> ")));
161             }
162 
163             specificToGenericStringHeader(sb);
164 
165             sb.append('(');
166             StringJoiner sj = new StringJoiner(",");
167             Type[] params = getGenericParameterTypes();
168             for (int j = 0; j < params.length; j++) {
169                 String param = params[j].getTypeName();
170                 if (isVarArgs() && (j == params.length - 1)) // replace T[] with T...
171                     param = param.replaceFirst("\\[\\]$", "...");
172                 sj.add(param);
173             }
174             sb.append(sj.toString());
175             sb.append(')');
176 
177             Type[] exceptionTypes = getGenericExceptionTypes();
178             if (exceptionTypes.length > 0) {
179                 sb.append(Arrays.stream(exceptionTypes)
180                           .map(Type::getTypeName)
181                           .collect(Collectors.joining(",", " throws ", "")));
182             }
183             return sb.toString();
184         } catch (Exception e) {
185             return "<" + e + ">";
186         }
187     }
188 
189     /**
190      * Generate toGenericString header information specific to a
191      * method or constructor.
192      */
193     abstract void specificToGenericStringHeader(StringBuilder sb);
194 
195     /**
196      * Returns the {@code Class} object representing the class or interface
197      * that declares the executable represented by this object.
198      */
199     public abstract Class<?> getDeclaringClass();
200 
201     /**
202      * Returns the name of the executable represented by this object.
203      */
204     public abstract String getName();
205 
206     /**
207      * {@return the Java language {@linkplain Modifier modifiers} for
208      * the executable represented by this object}
209      * @see #accessFlags
210      */
211     public abstract int getModifiers();
212 
213     /**
214      * {@return an unmodifiable set of the {@linkplain AccessFlag
215      * access flags} for the executable represented by this object,
216      * possibly empty}
217      * The {@code AccessFlags} may depend on the class file format version of the class.
218      *
219      * @see #getModifiers()
220      * @jvms 4.6 Methods
221      * @since 20
222      */
223     @Override
224     public Set<AccessFlag> accessFlags() {
225         int major = SharedSecrets.getJavaLangAccess().classFileFormatVersion(getDeclaringClass()) & 0xffff;
226         var cffv = ClassFileFormatVersion.fromMajor(major);
227         return AccessFlag.maskToAccessFlags(getModifiers(),
228                                             AccessFlag.Location.METHOD,
229                                             cffv);
230     }
231 
232     /**
233      * Returns an array of {@code TypeVariable} objects that represent the
234      * type variables declared by the generic declaration represented by this
235      * {@code GenericDeclaration} object, in declaration order.  Returns an
236      * array of length 0 if the underlying generic declaration declares no type
237      * variables.
238      *
239      * @return an array of {@code TypeVariable} objects that represent
240      *     the type variables declared by this generic declaration
241      * @throws GenericSignatureFormatError if the generic
242      *     signature of this generic declaration does not conform to
243      *     the format specified in
244      *     <cite>The Java Virtual Machine Specification</cite>
245      */
246     public abstract TypeVariable<?>[] getTypeParameters();
247 
248     // returns shared array of parameter types - must never give it out
249     // to the untrusted code...
250     abstract Class<?>[] getSharedParameterTypes();
251 
252     // returns shared array of exception types - must never give it out
253     // to the untrusted code...
254     abstract Class<?>[] getSharedExceptionTypes();
255 
256     /**
257      * Returns an array of {@code Class} objects that represent the formal
258      * parameter types, in declaration order, of the executable
259      * represented by this object.  Returns an array of length
260      * 0 if the underlying executable takes no parameters.
261      * Note that the constructors of some inner classes
262      * may have an implicitly declared parameter in addition to
263      * explicitly declared ones.
264      *
265      * @return the parameter types for the executable this object
266      * represents
267      */
268     public abstract Class<?>[] getParameterTypes();
269 
270     /**
271      * Returns the number of formal parameters (whether explicitly
272      * declared or implicitly declared or neither) for the executable
273      * represented by this object.
274      *
275      * @return The number of formal parameters for the executable this
276      * object represents
277      */
278     public abstract int getParameterCount();
279 
280     /**
281      * Returns an array of {@code Type} objects that represent the
282      * formal parameter types, in declaration order, of the executable
283      * represented by this object. An array of length 0 is returned if the
284      * underlying executable takes no parameters.  Note that the
285      * constructors of some inner classes may have an implicitly
286      * declared parameter in addition to explicitly declared ones.
287      * Also note that as a <a
288      * href="{@docRoot}/java.base/java/lang/reflect/package-summary.html#LanguageJvmModel">modeling
289      * artifact</a>, the number of returned parameters can differ
290      * depending on whether or not generic information is present. If
291      * generic information is present, only parameters explicitly
292      * present in the source will be returned; if generic information
293      * is not present, implicit and synthetic parameters may be
294      * returned as well.
295      *
296      * <p>If a formal parameter type is a parameterized type,
297      * the {@code Type} object returned for it must accurately reflect
298      * the actual type arguments used in the source code.
299      *
300      * <p>If a formal parameter type is a type variable or a parameterized
301      * type, it is created. Otherwise, it is resolved.
302      *
303      * @return an array of {@code Type}s that represent the formal
304      *     parameter types of the underlying executable, in declaration order
305      * @throws GenericSignatureFormatError
306      *     if the generic method signature does not conform to the format
307      *     specified in
308      *     <cite>The Java Virtual Machine Specification</cite>
309      * @throws TypeNotPresentException if any of the parameter
310      *     types of the underlying executable refers to a non-existent type
311      *     declaration
312      * @throws MalformedParameterizedTypeException if any of
313      *     the underlying executable's parameter types refer to a parameterized
314      *     type that cannot be instantiated for any reason
315      */
316     public Type[] getGenericParameterTypes() {
317         if (hasGenericInformation())
318             return getGenericInfo().getParameterTypes();
319         else
320             return getParameterTypes();
321     }
322 
323     /**
324      * Behaves like {@code getGenericParameterTypes}, but returns type
325      * information for all parameters, including synthetic parameters.
326      */
327     Type[] getAllGenericParameterTypes() {
328         final boolean genericInfo = hasGenericInformation();
329 
330         // Easy case: we don't have generic parameter information.  In
331         // this case, we just return the result of
332         // getParameterTypes().
333         if (!genericInfo) {
334             return getParameterTypes();
335         } else {
336             final boolean realParamData = hasRealParameterData();
337             final Type[] genericParamTypes = getGenericParameterTypes();
338             final Type[] nonGenericParamTypes = getSharedParameterTypes();
339             // If we have real parameter data, then we use the
340             // synthetic and mandate flags to our advantage.
341             if (realParamData) {
342                 final Type[] out = new Type[nonGenericParamTypes.length];
343                 final Parameter[] params = getParameters();
344                 int fromidx = 0;
345                 for (int i = 0; i < out.length; i++) {
346                     final Parameter param = params[i];
347                     if (param.isSynthetic() || param.isImplicit()) {
348                         // If we hit a synthetic or mandated parameter,
349                         // use the non generic parameter info.
350                         out[i] = nonGenericParamTypes[i];
351                     } else {
352                         // Otherwise, use the generic parameter info.
353                         out[i] = genericParamTypes[fromidx];
354                         fromidx++;
355                     }
356                 }
357                 return out;
358             } else {
359                 // Otherwise, use the non-generic parameter data.
360                 // Without method parameter reflection data, we have
361                 // no way to figure out which parameters are
362                 // synthetic/mandated, thus, no way to match up the
363                 // indexes.
364                 return genericParamTypes.length == nonGenericParamTypes.length ?
365                     genericParamTypes : getParameterTypes();
366             }
367         }
368     }
369 
370     /**
371      * {@return an array of {@code Parameter} objects representing
372      * all the parameters to the underlying executable represented by
373      * this object} An array of length 0 is returned if the executable
374      * has no parameters.
375      *
376      * <p>The parameters of the underlying executable do not necessarily
377      * have unique names, or names that are legal identifiers in the
378      * Java programming language (JLS {@jls 3.8}).
379      *
380      * @throws MalformedParametersException if the class file contains
381      * a MethodParameters attribute that is improperly formatted.
382      */
383     public Parameter[] getParameters() {
384         // TODO: This may eventually need to be guarded by security
385         // mechanisms similar to those in Field, Method, etc.
386         //
387         // Need to copy the cached array to prevent users from messing
388         // with it.  Since parameters are immutable, we can
389         // shallow-copy.
390         return parameterData().parameters.clone();
391     }
392 
393     private Parameter[] synthesizeAllParams() {
394         final int realparams = getParameterCount();
395         final Parameter[] out = new Parameter[realparams];
396         for (int i = 0; i < realparams; i++)
397             // TODO: is there a way to synthetically derive the
398             // modifiers?  Probably not in the general case, since
399             // we'd have no way of knowing about them, but there
400             // may be specific cases.
401             out[i] = new Parameter("arg" + i, 0, this, i);
402         return out;
403     }
404 
405     private void verifyParameters(final Parameter[] parameters) {
406         final int mask = Modifier.FINAL | Modifier.SYNTHETIC | Modifier.MANDATED;
407 
408         if (getParameterCount() != parameters.length)
409             throw new MalformedParametersException("Wrong number of parameters in MethodParameters attribute");
410 
411         for (Parameter parameter : parameters) {
412             final String name = parameter.getRealName();
413             final int mods = parameter.getModifiers();
414 
415             if (name != null) {
416                 if (name.isEmpty() || name.indexOf('.') != -1 ||
417                     name.indexOf(';') != -1 || name.indexOf('[') != -1 ||
418                     name.indexOf('/') != -1) {
419                     throw new MalformedParametersException("Invalid parameter name \"" + name + "\"");
420                 }
421             }
422 
423             if (mods != (mods & mask)) {
424                 throw new MalformedParametersException("Invalid parameter modifiers");
425             }
426         }
427     }
428 
429 
430     boolean hasRealParameterData() {
431         return parameterData().isReal;
432     }
433 
434     private ParameterData parameterData() {
435         ParameterData parameterData = this.parameterData;
436         if (parameterData != null) {
437             return parameterData;
438         }
439 
440         Parameter[] tmp;
441         // Go to the JVM to get them
442         try {
443             tmp = getParameters0();
444         } catch (IllegalArgumentException e) {
445             // Rethrow ClassFormatErrors
446             throw new MalformedParametersException("Invalid constant pool index");
447         }
448 
449         // If we get back nothing, then synthesize parameters
450         if (tmp == null) {
451             tmp = synthesizeAllParams();
452             parameterData = new ParameterData(tmp, false);
453         } else {
454             verifyParameters(tmp);
455             parameterData = new ParameterData(tmp, true);
456         }
457         return this.parameterData = parameterData;
458     }
459 
460     private transient @Stable ParameterData parameterData;
461 
462     record ParameterData(@Stable Parameter[] parameters, boolean isReal) {}
463 
464     private native Parameter[] getParameters0();
465     native byte[] getTypeAnnotationBytes0();
466 
467     // Needed by reflectaccess
468     byte[] getTypeAnnotationBytes() {
469         return getTypeAnnotationBytes0();
470     }
471 
472     /**
473      * Returns an array of {@code Class} objects that represent the
474      * types of exceptions declared to be thrown by the underlying
475      * executable represented by this object.  Returns an array of
476      * length 0 if the executable declares no exceptions in its {@code
477      * throws} clause.
478      *
479      * @return the exception types declared as being thrown by the
480      * executable this object represents
481      */
482     public abstract Class<?>[] getExceptionTypes();
483 
484     /**
485      * Returns an array of {@code Type} objects that represent the
486      * exceptions declared to be thrown by this executable object.
487      * Returns an array of length 0 if the underlying executable declares
488      * no exceptions in its {@code throws} clause.
489      *
490      * <p>If an exception type is a type variable or a parameterized
491      * type, it is created. Otherwise, it is resolved.
492      *
493      * @return an array of Types that represent the exception types
494      *     thrown by the underlying executable
495      * @throws GenericSignatureFormatError
496      *     if the generic method signature does not conform to the format
497      *     specified in
498      *     <cite>The Java Virtual Machine Specification</cite>
499      * @throws TypeNotPresentException if the underlying executable's
500      *     {@code throws} clause refers to a non-existent type declaration
501      * @throws MalformedParameterizedTypeException if
502      *     the underlying executable's {@code throws} clause refers to a
503      *     parameterized type that cannot be instantiated for any reason
504      */
505     public Type[] getGenericExceptionTypes() {
506         Type[] result;
507         if (hasGenericInformation() &&
508             ((result = getGenericInfo().getExceptionTypes()).length > 0))
509             return result;
510         else
511             return getExceptionTypes();
512     }
513 
514     /**
515      * {@return a string describing this {@code Executable}, including
516      * any type parameters}
517      */
518     public abstract String toGenericString();
519 
520     /**
521      * {@return {@code true} if this executable was declared to take a
522      * variable number of arguments; returns {@code false} otherwise}
523      */
524     public boolean isVarArgs()  {
525         return (getModifiers() & Modifier.VARARGS) != 0;
526     }
527 
528     /**
529      * Returns {@code true} if this executable is a synthetic
530      * construct; returns {@code false} otherwise.
531      *
532      * @return true if and only if this executable is a synthetic
533      * construct as defined by
534      * <cite>The Java Language Specification</cite>.
535      * @jls 13.1 The Form of a Binary
536      * @jvms 4.6 Methods
537      */
538     public boolean isSynthetic() {
539         return Modifier.isSynthetic(getModifiers());
540     }
541 
542     /**
543      * Returns an array of arrays of {@code Annotation}s that
544      * represent the annotations on the formal parameters, in
545      * declaration order, of the {@code Executable} represented by
546      * this object.  Synthetic and mandated parameters (see
547      * explanation below), such as the outer "this" parameter to an
548      * inner class constructor will be represented in the returned
549      * array.  If the executable has no parameters (meaning no formal,
550      * no synthetic, and no mandated parameters), a zero-length array
551      * will be returned.  If the {@code Executable} has one or more
552      * parameters, a nested array of length zero is returned for each
553      * parameter with no annotations. The annotation objects contained
554      * in the returned arrays are serializable.  The caller of this
555      * method is free to modify the returned arrays; it will have no
556      * effect on the arrays returned to other callers.
557      *
558      * A compiler may add extra parameters that are implicitly
559      * declared in source ("mandated"), as well as parameters that
560      * are neither implicitly nor explicitly declared in source
561      * ("synthetic") to the parameter list for a method.  See {@link
562      * java.lang.reflect.Parameter} for more information.
563      *
564      * <p>Note that any annotations returned by this method are
565      * declaration annotations.
566      *
567      * @see java.lang.reflect.Parameter
568      * @see java.lang.reflect.Parameter#getAnnotations
569      * @return an array of arrays that represent the annotations on
570      *    the formal and implicit parameters, in declaration order, of
571      *    the executable represented by this object
572      */
573     public abstract Annotation[][] getParameterAnnotations();
574 
575     Annotation[][] sharedGetParameterAnnotations(Class<?>[] parameterTypes,
576                                                  byte[] parameterAnnotations) {
577         int numParameters = parameterTypes.length;
578         if (parameterAnnotations == null)
579             return new Annotation[numParameters][0];
580 
581         Annotation[][] result = parseParameterAnnotations(parameterAnnotations);
582 
583         if (result.length != numParameters &&
584             handleParameterNumberMismatch(result.length, parameterTypes)) {
585             Annotation[][] tmp = new Annotation[numParameters][];
586             // Shift annotations down to account for any implicit leading parameters
587             System.arraycopy(result, 0, tmp, numParameters - result.length, result.length);
588             for (int i = 0; i < numParameters - result.length; i++) {
589                 tmp[i] = new Annotation[0];
590             }
591             result = tmp;
592         }
593         return result;
594     }
595 
596     abstract boolean handleParameterNumberMismatch(int resultLength, Class<?>[] parameterTypes);
597 
598     /**
599      * {@inheritDoc}
600      * @throws NullPointerException  {@inheritDoc}
601      */
602     @Override
603     public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
604         Objects.requireNonNull(annotationClass);
605         return annotationClass.cast(declaredAnnotations().get(annotationClass));
606     }
607 
608     /**
609      * {@inheritDoc}
610      *
611      * @throws NullPointerException {@inheritDoc}
612      */
613     @Override
614     public <T extends Annotation> T[] getAnnotationsByType(Class<T> annotationClass) {
615         Objects.requireNonNull(annotationClass);
616 
617         return AnnotationSupport.getDirectlyAndIndirectlyPresent(declaredAnnotations(), annotationClass);
618     }
619 
620     /**
621      * {@inheritDoc}
622      */
623     @Override
624     public Annotation[] getDeclaredAnnotations()  {
625         return AnnotationParser.toArray(declaredAnnotations());
626     }
627 
628     private transient volatile Map<Class<? extends Annotation>, Annotation> declaredAnnotations;
629 
630     private Map<Class<? extends Annotation>, Annotation> declaredAnnotations() {
631         Map<Class<? extends Annotation>, Annotation> declAnnos;
632         if ((declAnnos = declaredAnnotations) == null) {
633             synchronized (this) {
634                 if ((declAnnos = declaredAnnotations) == null) {
635                     Executable root = (Executable)getRoot();
636                     if (root != null) {
637                         declAnnos = root.declaredAnnotations();
638                     } else {
639                         declAnnos = AnnotationParser.parseAnnotations(
640                                 getAnnotationBytes(),
641                                 SharedSecrets.getJavaLangAccess().
642                                         getConstantPool(getDeclaringClass()),
643                                 getDeclaringClass()
644                         );
645                     }
646                     declaredAnnotations = declAnnos;
647                 }
648             }
649         }
650         return declAnnos;
651     }
652 
653     /**
654      * Returns an {@code AnnotatedType} object that represents the use of a type to
655      * specify the return type of the method/constructor represented by this
656      * Executable.
657      *
658      * If this {@code Executable} object represents a constructor, the {@code
659      * AnnotatedType} object represents the type of the constructed object.
660      *
661      * If this {@code Executable} object represents a method, the {@code
662      * AnnotatedType} object represents the use of a type to specify the return
663      * type of the method.
664      *
665      * @return an object representing the return type of the method
666      * or constructor represented by this {@code Executable}
667      */
668     public abstract AnnotatedType getAnnotatedReturnType();
669 
670     /* Helper for subclasses of Executable.
671      *
672      * Returns an AnnotatedType object that represents the use of a type to
673      * specify the return type of the method/constructor represented by this
674      * Executable.
675      */
676     AnnotatedType getAnnotatedReturnType0(Type returnType) {
677         return TypeAnnotationParser.buildAnnotatedType(getTypeAnnotationBytes0(),
678                 SharedSecrets.getJavaLangAccess().
679                         getConstantPool(getDeclaringClass()),
680                 this,
681                 getDeclaringClass(),
682                 returnType,
683                 TypeAnnotation.TypeAnnotationTarget.METHOD_RETURN);
684     }
685 
686     /**
687      * Returns an {@code AnnotatedType} object that represents the use of a
688      * type to specify the receiver type of the method/constructor represented
689      * by this {@code Executable} object.
690      *
691      * The receiver type of a method/constructor is available only if the
692      * method/constructor has a receiver parameter (JLS {@jls 8.4.1}). If this {@code
693      * Executable} object <em>represents an instance method or represents a
694      * constructor of an inner member class</em>, and the
695      * method/constructor <em>either</em> has no receiver parameter or has a
696      * receiver parameter with no annotations on its type, then the return
697      * value is an {@code AnnotatedType} object representing an element with no
698      * annotations.
699      *
700      * If this {@code Executable} object represents a static method or
701      * represents a constructor of a top level, static member, local, or
702      * anonymous class, then the return value is null.
703      *
704      * @return an object representing the receiver type of the method or
705      * constructor represented by this {@code Executable} or {@code null} if
706      * this {@code Executable} can not have a receiver parameter
707      *
708      * @jls 8.4 Method Declarations
709      * @jls 8.4.1 Formal Parameters
710      * @jls 8.8 Constructor Declarations
711      */
712     public AnnotatedType getAnnotatedReceiverType() {
713         if (Modifier.isStatic(this.getModifiers()))
714             return null;
715         return TypeAnnotationParser.buildAnnotatedType(getTypeAnnotationBytes0(),
716                 SharedSecrets.getJavaLangAccess().
717                         getConstantPool(getDeclaringClass()),
718                 this,
719                 getDeclaringClass(),
720                 parameterize(getDeclaringClass()),
721                 TypeAnnotation.TypeAnnotationTarget.METHOD_RECEIVER);
722     }
723 
724     Type parameterize(Class<?> c) {
725         Class<?> ownerClass = c.getDeclaringClass();
726         TypeVariable<?>[] typeVars = c.getTypeParameters();
727 
728         // base case, static nested classes, according to JLS 8.1.3, has no
729         // enclosing instance, therefore its owner is not generified.
730         if (ownerClass == null || Modifier.isStatic(c.getModifiers())) {
731             if (typeVars.length == 0)
732                 return c;
733             else
734                 return ParameterizedTypeImpl.make(c, typeVars, null);
735         }
736 
737         // Resolve owner
738         Type ownerType = parameterize(ownerClass);
739         if (ownerType instanceof Class<?> && typeVars.length == 0) // We have yet to encounter type parameters
740             return c;
741         else
742             return ParameterizedTypeImpl.make(c, typeVars, ownerType);
743     }
744 
745     /**
746      * Returns an array of {@code AnnotatedType} objects that represent the use
747      * of types to specify formal parameter types of the method/constructor
748      * represented by this Executable. The order of the objects in the array
749      * corresponds to the order of the formal parameter types in the
750      * declaration of the method/constructor.
751      *
752      * Returns an array of length 0 if the method/constructor declares no
753      * parameters.
754      * Note that the constructors of some inner classes
755      * may have an implicitly declared parameter in addition to
756      * explicitly declared ones.
757      *
758      * @return an array of objects representing the types of the
759      * formal parameters of the method or constructor represented by this
760      * {@code Executable}
761      */
762     public AnnotatedType[] getAnnotatedParameterTypes() {
763         return TypeAnnotationParser.buildAnnotatedTypes(getTypeAnnotationBytes0(),
764                 SharedSecrets.getJavaLangAccess().
765                         getConstantPool(getDeclaringClass()),
766                 this,
767                 getDeclaringClass(),
768                 getAllGenericParameterTypes(),
769                 TypeAnnotation.TypeAnnotationTarget.METHOD_FORMAL_PARAMETER);
770     }
771 
772     /**
773      * Returns an array of {@code AnnotatedType} objects that represent the use
774      * of types to specify the declared exceptions of the method/constructor
775      * represented by this Executable. The order of the objects in the array
776      * corresponds to the order of the exception types in the declaration of
777      * the method/constructor.
778      *
779      * Returns an array of length 0 if the method/constructor declares no
780      * exceptions.
781      *
782      * @return an array of objects representing the declared
783      * exceptions of the method or constructor represented by this {@code
784      * Executable}
785      */
786     public AnnotatedType[] getAnnotatedExceptionTypes() {
787         return TypeAnnotationParser.buildAnnotatedTypes(getTypeAnnotationBytes0(),
788                 SharedSecrets.getJavaLangAccess().
789                         getConstantPool(getDeclaringClass()),
790                 this,
791                 getDeclaringClass(),
792                 getGenericExceptionTypes(),
793                 TypeAnnotation.TypeAnnotationTarget.THROWS);
794     }
795 }