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      *
218      * @see #getModifiers()
219      * @jvms 4.6 Methods
220      * @since 20
221      */
222     @Override
223     public Set<AccessFlag> accessFlags() {
224         return AccessFlag.maskToAccessFlags(getModifiers(),
225                                             AccessFlag.Location.METHOD);
226     }
227 
228     /**
229      * Returns an array of {@code TypeVariable} objects that represent the
230      * type variables declared by the generic declaration represented by this
231      * {@code GenericDeclaration} object, in declaration order.  Returns an
232      * array of length 0 if the underlying generic declaration declares no type
233      * variables.
234      *
235      * @return an array of {@code TypeVariable} objects that represent
236      *     the type variables declared by this generic declaration
237      * @throws GenericSignatureFormatError if the generic
238      *     signature of this generic declaration does not conform to
239      *     the format specified in
240      *     <cite>The Java Virtual Machine Specification</cite>
241      */
242     public abstract TypeVariable<?>[] getTypeParameters();
243 
244     // returns shared array of parameter types - must never give it out
245     // to the untrusted code...
246     abstract Class<?>[] getSharedParameterTypes();
247 
248     // returns shared array of exception types - must never give it out
249     // to the untrusted code...
250     abstract Class<?>[] getSharedExceptionTypes();
251 
252     /**
253      * Returns an array of {@code Class} objects that represent the formal
254      * parameter types, in declaration order, of the executable
255      * represented by this object.  Returns an array of length
256      * 0 if the underlying executable takes no parameters.
257      * Note that the constructors of some inner classes
258      * may have an {@linkplain java.compiler/javax.lang.model.util.Elements.Origin#MANDATED
259      * implicitly declared} parameter in addition to explicitly
260      * declared ones.
261      * Also note that compact constructors of a record class may have
262      * {@linkplain java.compiler/javax.lang.model.util.Elements.Origin#MANDATED
263      * implicitly declared} parameters.
264      *
265      * @return the parameter types for the executable this object
266      * represents
267      */
268     @SuppressWarnings("doclint:reference") // cross-module links
269     public abstract Class<?>[] getParameterTypes();
270 
271     /**
272      * Returns the number of formal parameters (whether explicitly
273      * declared or implicitly declared or neither) for the executable
274      * represented by this object.
275      *
276      * @return The number of formal parameters for the executable this
277      * object represents
278      */
279     public abstract int getParameterCount();
280 
281     /**
282      * Returns an array of {@code Type} objects that represent the
283      * formal parameter types, in declaration order, of the executable
284      * represented by this object. An array of length 0 is returned if the
285      * underlying executable takes no parameters.  Note that the
286      * constructors of some inner classes may have an implicitly
287      * declared parameter in addition to explicitly declared ones.
288      * Compact constructors of a record class may also have
289      * {@linkplain java.compiler/javax.lang.model.util.Elements.Origin#MANDATED
290      * implicitly declared} parameters,
291      * but they are a special case and thus considered as if they had
292      * been explicitly declared in the source.
293      * Finally note that as a {@link java.lang.reflect##LanguageJvmModel
294      * modeling artifact}, the number of returned parameters can differ
295      * depending on whether or not generic information is present. If
296      * generic information is present, parameters explicitly
297      * present in the source or parameters of compact constructors
298      * of a record class will be returned.
299      * Note that parameters of compact constructors of a record class are a special case,
300      * as they are not explicitly present in the source, and its type will be returned
301      * regardless of the parameters being
302      * {@linkplain java.compiler/javax.lang.model.util.Elements.Origin#MANDATED
303      * implicitly declared} or not.
304      * If generic information is not present, implicit and synthetic parameters may be
305      * returned as well.
306      *
307      * <p>If a formal parameter type is a parameterized type,
308      * the {@code Type} object returned for it must accurately reflect
309      * the actual type arguments used in the source code. This assertion also
310      * applies to the parameters of compact constructors of a record class,
311      * independently of them being
312      * {@linkplain java.compiler/javax.lang.model.util.Elements.Origin#MANDATED
313      * implicitly declared} or not.
314      *
315      * <p>If a formal parameter type is a type variable or a parameterized
316      * type, it is created. Otherwise, it is resolved.
317      *
318      * @return an array of {@code Type}s that represent the formal
319      *     parameter types of the underlying executable, in declaration order
320      * @throws GenericSignatureFormatError
321      *     if the generic method signature does not conform to the format
322      *     specified in
323      *     <cite>The Java Virtual Machine Specification</cite>
324      * @throws TypeNotPresentException if any of the parameter
325      *     types of the underlying executable refers to a non-existent type
326      *     declaration
327      * @throws MalformedParameterizedTypeException if any of
328      *     the underlying executable's parameter types refer to a parameterized
329      *     type that cannot be instantiated for any reason
330      */
331     @SuppressWarnings("doclint:reference") // cross-module links
332     public Type[] getGenericParameterTypes() {
333         if (hasGenericInformation())
334             return getGenericInfo().getParameterTypes();
335         else
336             return getParameterTypes();
337     }
338 
339     /**
340      * Behaves like {@code getGenericParameterTypes}, but returns type
341      * information for all parameters, including synthetic parameters.
342      */
343     Type[] getAllGenericParameterTypes() {
344         final boolean genericInfo = hasGenericInformation();
345 
346         // Easy case: we don't have generic parameter information.  In
347         // this case, we just return the result of
348         // getParameterTypes().
349         if (!genericInfo) {
350             return getParameterTypes();
351         } else {
352             final boolean realParamData = hasRealParameterData();
353             final Type[] genericParamTypes = getGenericParameterTypes();
354             final Type[] nonGenericParamTypes = getSharedParameterTypes();
355             // If we have real parameter data, then we use the
356             // synthetic and mandate flags to our advantage.
357             if (realParamData) {
358                 if (getDeclaringClass().isRecord() && this instanceof Constructor) {
359                     /* we could be seeing a compact constructor of a record class
360                      * its parameters are mandated but we should be able to retrieve
361                      * its generic information if present
362                      */
363                     if (genericParamTypes.length == nonGenericParamTypes.length) {
364                         return genericParamTypes;
365                     } else {
366                         return nonGenericParamTypes.clone();
367                     }
368                 } else {
369                     final Type[] out = new Type[nonGenericParamTypes.length];
370                     final Parameter[] params = getParameters();
371                     int fromidx = 0;
372                     for (int i = 0; i < out.length; i++) {
373                         final Parameter param = params[i];
374                         if (param.isSynthetic() || param.isImplicit()) {
375                             // If we hit a synthetic or mandated parameter,
376                             // use the non generic parameter info.
377                             out[i] = nonGenericParamTypes[i];
378                         } else {
379                             // Otherwise, use the generic parameter info.
380                             out[i] = genericParamTypes[fromidx];
381                             fromidx++;
382                         }
383                     }
384                     return out;
385                 }
386             } else {
387                 // Otherwise, use the non-generic parameter data.
388                 // Without method parameter reflection data, we have
389                 // no way to figure out which parameters are
390                 // synthetic/mandated, thus, no way to match up the
391                 // indexes.
392                 return genericParamTypes.length == nonGenericParamTypes.length ?
393                     genericParamTypes : getParameterTypes();
394             }
395         }
396     }
397 
398     /**
399      * {@return an array of {@code Parameter} objects representing
400      * all the parameters to the underlying executable represented by
401      * this object} An array of length 0 is returned if the executable
402      * has no parameters.
403      *
404      * <p>The parameters of the underlying executable do not necessarily
405      * have unique names, or names that are legal identifiers in the
406      * Java programming language (JLS {@jls 3.8}).
407      *
408      * @throws MalformedParametersException if the class file contains
409      * a MethodParameters attribute that is improperly formatted.
410      */
411     public Parameter[] getParameters() {
412         // TODO: This may eventually need to be guarded by security
413         // mechanisms similar to those in Field, Method, etc.
414         //
415         // Need to copy the cached array to prevent users from messing
416         // with it.  Since parameters are immutable, we can
417         // shallow-copy.
418         return parameterData().parameters.clone();
419     }
420 
421     private Parameter[] synthesizeAllParams() {
422         final int realparams = getParameterCount();
423         final Parameter[] out = new Parameter[realparams];
424         for (int i = 0; i < realparams; i++)
425             // TODO: is there a way to synthetically derive the
426             // modifiers?  Probably not in the general case, since
427             // we'd have no way of knowing about them, but there
428             // may be specific cases.
429             out[i] = new Parameter("arg" + i, 0, this, i);
430         return out;
431     }
432 
433     private void verifyParameters(final Parameter[] parameters) {
434         final int mask = Modifier.FINAL | Modifier.SYNTHETIC | Modifier.MANDATED;
435 
436         if (getParameterCount() != parameters.length)
437             throw new MalformedParametersException("Wrong number of parameters in MethodParameters attribute");
438 
439         for (Parameter parameter : parameters) {
440             final String name = parameter.getRealName();
441             final int mods = parameter.getModifiers();
442 
443             if (name != null) {
444                 if (name.isEmpty() || name.indexOf('.') != -1 ||
445                     name.indexOf(';') != -1 || name.indexOf('[') != -1 ||
446                     name.indexOf('/') != -1) {
447                     throw new MalformedParametersException("Invalid parameter name \"" + name + "\"");
448                 }
449             }
450 
451             if (mods != (mods & mask)) {
452                 throw new MalformedParametersException("Invalid parameter modifiers");
453             }
454         }
455     }
456 
457 
458     boolean hasRealParameterData() {
459         return parameterData().isReal;
460     }
461 
462     private ParameterData parameterData() {
463         ParameterData parameterData = this.parameterData;
464         if (parameterData != null) {
465             return parameterData;
466         }
467 
468         Parameter[] tmp;
469         // Go to the JVM to get them
470         try {
471             tmp = getParameters0();
472         } catch (IllegalArgumentException e) {
473             // Rethrow ClassFormatErrors
474             throw new MalformedParametersException("Invalid constant pool index");
475         }
476 
477         // If we get back nothing, then synthesize parameters
478         if (tmp == null) {
479             tmp = synthesizeAllParams();
480             parameterData = new ParameterData(tmp, false);
481         } else {
482             verifyParameters(tmp);
483             parameterData = new ParameterData(tmp, true);
484         }
485         return this.parameterData = parameterData;
486     }
487 
488     private transient @Stable ParameterData parameterData;
489 
490     record ParameterData(@Stable Parameter[] parameters, boolean isReal) {}
491 
492     private native Parameter[] getParameters0();
493     native byte[] getTypeAnnotationBytes0();
494 
495     // Needed by reflectaccess
496     byte[] getTypeAnnotationBytes() {
497         return getTypeAnnotationBytes0();
498     }
499 
500     /**
501      * Returns an array of {@code Class} objects that represent the
502      * types of exceptions declared to be thrown by the underlying
503      * executable represented by this object.  Returns an array of
504      * length 0 if the executable declares no exceptions in its {@code
505      * throws} clause.
506      *
507      * @return the exception types declared as being thrown by the
508      * executable this object represents
509      */
510     public abstract Class<?>[] getExceptionTypes();
511 
512     /**
513      * Returns an array of {@code Type} objects that represent the
514      * exceptions declared to be thrown by this executable object.
515      * Returns an array of length 0 if the underlying executable declares
516      * no exceptions in its {@code throws} clause.
517      *
518      * <p>If an exception type is a type variable or a parameterized
519      * type, it is created. Otherwise, it is resolved.
520      *
521      * @return an array of Types that represent the exception types
522      *     thrown by the underlying executable
523      * @throws GenericSignatureFormatError
524      *     if the generic method signature does not conform to the format
525      *     specified in
526      *     <cite>The Java Virtual Machine Specification</cite>
527      * @throws TypeNotPresentException if the underlying executable's
528      *     {@code throws} clause refers to a non-existent type declaration
529      * @throws MalformedParameterizedTypeException if
530      *     the underlying executable's {@code throws} clause refers to a
531      *     parameterized type that cannot be instantiated for any reason
532      */
533     public Type[] getGenericExceptionTypes() {
534         Type[] result;
535         if (hasGenericInformation() &&
536             ((result = getGenericInfo().getExceptionTypes()).length > 0))
537             return result;
538         else
539             return getExceptionTypes();
540     }
541 
542     /**
543      * {@return a string describing this {@code Executable}, including
544      * any type parameters}
545      */
546     public abstract String toGenericString();
547 
548     /**
549      * {@return {@code true} if this executable was declared to take a
550      * variable number of arguments; returns {@code false} otherwise}
551      */
552     public boolean isVarArgs()  {
553         return (getModifiers() & Modifier.VARARGS) != 0;
554     }
555 
556     /**
557      * Returns {@code true} if this executable is a synthetic
558      * construct; returns {@code false} otherwise.
559      *
560      * @return true if and only if this executable is a synthetic
561      * construct as defined by
562      * <cite>The Java Language Specification</cite>.
563      * @jls 13.1 The Form of a Binary
564      * @jvms 4.6 Methods
565      */
566     public boolean isSynthetic() {
567         return Modifier.isSynthetic(getModifiers());
568     }
569 
570     /**
571      * Returns an array of arrays of {@code Annotation}s that
572      * represent the annotations on the formal parameters, in
573      * declaration order, of the {@code Executable} represented by
574      * this object.  Synthetic and mandated parameters (see
575      * explanation below), such as the outer "this" parameter to an
576      * inner class constructor will be represented in the returned
577      * array.  If the executable has no parameters (meaning no formal,
578      * no synthetic, and no mandated parameters), a zero-length array
579      * will be returned.  If the {@code Executable} has one or more
580      * parameters, a nested array of length zero is returned for each
581      * parameter with no annotations. The annotation objects contained
582      * in the returned arrays are serializable.  The caller of this
583      * method is free to modify the returned arrays; it will have no
584      * effect on the arrays returned to other callers.
585      *
586      * A compiler may add extra parameters that are implicitly
587      * declared in source ("mandated"), as well as parameters that
588      * are neither implicitly nor explicitly declared in source
589      * ("synthetic") to the parameter list for a method.  See {@link
590      * java.lang.reflect.Parameter} for more information.
591      *
592      * <p>Note that any annotations returned by this method are
593      * declaration annotations.
594      *
595      * @see java.lang.reflect.Parameter
596      * @see java.lang.reflect.Parameter#getAnnotations
597      * @return an array of arrays that represent the annotations on
598      *    the formal and implicit parameters, in declaration order, of
599      *    the executable represented by this object
600      */
601     public abstract Annotation[][] getParameterAnnotations();
602 
603     Annotation[][] sharedGetParameterAnnotations(Class<?>[] parameterTypes,
604                                                  byte[] parameterAnnotations) {
605         int numParameters = parameterTypes.length;
606         if (parameterAnnotations == null)
607             return new Annotation[numParameters][0];
608 
609         Annotation[][] result = parseParameterAnnotations(parameterAnnotations);
610 
611         if (result.length != numParameters &&
612             handleParameterNumberMismatch(result.length, parameterTypes)) {
613             Annotation[][] tmp = new Annotation[numParameters][];
614             // Shift annotations down to account for any implicit leading parameters
615             System.arraycopy(result, 0, tmp, numParameters - result.length, result.length);
616             for (int i = 0; i < numParameters - result.length; i++) {
617                 tmp[i] = new Annotation[0];
618             }
619             result = tmp;
620         }
621         return result;
622     }
623 
624     abstract boolean handleParameterNumberMismatch(int resultLength, Class<?>[] parameterTypes);
625 
626     /**
627      * {@inheritDoc}
628      * @throws NullPointerException  {@inheritDoc}
629      */
630     @Override
631     public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
632         Objects.requireNonNull(annotationClass);
633         return annotationClass.cast(declaredAnnotations().get(annotationClass));
634     }
635 
636     /**
637      * {@inheritDoc}
638      *
639      * @throws NullPointerException {@inheritDoc}
640      */
641     @Override
642     public <T extends Annotation> T[] getAnnotationsByType(Class<T> annotationClass) {
643         Objects.requireNonNull(annotationClass);
644 
645         return AnnotationSupport.getDirectlyAndIndirectlyPresent(declaredAnnotations(), annotationClass);
646     }
647 
648     /**
649      * {@inheritDoc}
650      */
651     @Override
652     public Annotation[] getDeclaredAnnotations()  {
653         return AnnotationParser.toArray(declaredAnnotations());
654     }
655 
656     private transient volatile Map<Class<? extends Annotation>, Annotation> declaredAnnotations;
657 
658     private Map<Class<? extends Annotation>, Annotation> declaredAnnotations() {
659         Map<Class<? extends Annotation>, Annotation> declAnnos;
660         if ((declAnnos = declaredAnnotations) == null) {
661             synchronized (this) {
662                 if ((declAnnos = declaredAnnotations) == null) {
663                     Executable root = (Executable)getRoot();
664                     if (root != null) {
665                         declAnnos = root.declaredAnnotations();
666                     } else {
667                         declAnnos = AnnotationParser.parseAnnotations(
668                                 getAnnotationBytes(),
669                                 SharedSecrets.getJavaLangAccess().
670                                         getConstantPool(getDeclaringClass()),
671                                 getDeclaringClass()
672                         );
673                     }
674                     declaredAnnotations = declAnnos;
675                 }
676             }
677         }
678         return declAnnos;
679     }
680 
681     /**
682      * Returns an {@code AnnotatedType} object that represents the use of a type to
683      * specify the return type of the method/constructor represented by this
684      * Executable.
685      *
686      * If this {@code Executable} object represents a constructor, the {@code
687      * AnnotatedType} object represents the type of the constructed object.
688      *
689      * If this {@code Executable} object represents a method, the {@code
690      * AnnotatedType} object represents the use of a type to specify the return
691      * type of the method.
692      *
693      * @return an object representing the return type of the method
694      * or constructor represented by this {@code Executable}
695      */
696     public abstract AnnotatedType getAnnotatedReturnType();
697 
698     /* Helper for subclasses of Executable.
699      *
700      * Returns an AnnotatedType object that represents the use of a type to
701      * specify the return type of the method/constructor represented by this
702      * Executable.
703      */
704     AnnotatedType getAnnotatedReturnType0(Type returnType) {
705         return TypeAnnotationParser.buildAnnotatedType(getTypeAnnotationBytes0(),
706                 SharedSecrets.getJavaLangAccess().
707                         getConstantPool(getDeclaringClass()),
708                 this,
709                 getDeclaringClass(),
710                 returnType,
711                 TypeAnnotation.TypeAnnotationTarget.METHOD_RETURN);
712     }
713 
714     /**
715      * Returns an {@code AnnotatedType} object that represents the use of a
716      * type to specify the receiver type of the method/constructor represented
717      * by this {@code Executable} object.
718      *
719      * The receiver type of a method/constructor is available only if the
720      * method/constructor has a receiver parameter (JLS {@jls 8.4.1}). If this {@code
721      * Executable} object <em>represents an instance method or represents a
722      * constructor of an inner member class</em>, and the
723      * method/constructor <em>either</em> has no receiver parameter or has a
724      * receiver parameter with no annotations on its type, then the return
725      * value is an {@code AnnotatedType} object representing an element with no
726      * annotations.
727      *
728      * If this {@code Executable} object represents a static method or
729      * represents a constructor of a top level, static member, local, or
730      * anonymous class, then the return value is null.
731      *
732      * @return an object representing the receiver type of the method or
733      * constructor represented by this {@code Executable} or {@code null} if
734      * this {@code Executable} can not have a receiver parameter
735      *
736      * @jls 8.4 Method Declarations
737      * @jls 8.4.1 Formal Parameters
738      * @jls 8.8 Constructor Declarations
739      */
740     public AnnotatedType getAnnotatedReceiverType() {
741         if (Modifier.isStatic(this.getModifiers()))
742             return null;
743         return TypeAnnotationParser.buildAnnotatedType(getTypeAnnotationBytes0(),
744                 SharedSecrets.getJavaLangAccess().
745                         getConstantPool(getDeclaringClass()),
746                 this,
747                 getDeclaringClass(),
748                 parameterize(getDeclaringClass()),
749                 TypeAnnotation.TypeAnnotationTarget.METHOD_RECEIVER);
750     }
751 
752     Type parameterize(Class<?> c) {
753         Class<?> ownerClass = c.getDeclaringClass();
754         TypeVariable<?>[] typeVars = c.getTypeParameters();
755 
756         // base case, static nested classes, according to JLS 8.1.3, has no
757         // enclosing instance, therefore its owner is not generified.
758         if (ownerClass == null || Modifier.isStatic(c.getModifiers())) {
759             if (typeVars.length == 0)
760                 return c;
761             else
762                 return ParameterizedTypeImpl.make(c, typeVars, null);
763         }
764 
765         // Resolve owner
766         Type ownerType = parameterize(ownerClass);
767         if (ownerType instanceof Class<?> && typeVars.length == 0) // We have yet to encounter type parameters
768             return c;
769         else
770             return ParameterizedTypeImpl.make(c, typeVars, ownerType);
771     }
772 
773     /**
774      * Returns an array of {@code AnnotatedType} objects that represent the use
775      * of types to specify formal parameter types of the method/constructor
776      * represented by this Executable. The order of the objects in the array
777      * corresponds to the order of the formal parameter types in the
778      * declaration of the method/constructor.
779      *
780      * Returns an array of length 0 if the method/constructor declares no
781      * parameters.
782      * Note that the constructors of some inner classes
783      * may have an
784      * {@linkplain java.compiler/javax.lang.model.util.Elements.Origin#MANDATED
785      * implicitly declared} parameter in addition to explicitly declared ones.
786      * Also note that compact constructors of a record class may have
787      * {@linkplain java.compiler/javax.lang.model.util.Elements.Origin#MANDATED
788      * implicitly declared} parameters.
789      *
790      * @return an array of objects representing the types of the
791      * formal parameters of the method or constructor represented by this
792      * {@code Executable}
793      */
794     @SuppressWarnings("doclint:reference") // cross-module links
795     public AnnotatedType[] getAnnotatedParameterTypes() {
796         return TypeAnnotationParser.buildAnnotatedTypes(getTypeAnnotationBytes0(),
797                 SharedSecrets.getJavaLangAccess().
798                         getConstantPool(getDeclaringClass()),
799                 this,
800                 getDeclaringClass(),
801                 getAllGenericParameterTypes(),
802                 TypeAnnotation.TypeAnnotationTarget.METHOD_FORMAL_PARAMETER);
803     }
804 
805     /**
806      * Returns an array of {@code AnnotatedType} objects that represent the use
807      * of types to specify the declared exceptions of the method/constructor
808      * represented by this Executable. The order of the objects in the array
809      * corresponds to the order of the exception types in the declaration of
810      * the method/constructor.
811      *
812      * Returns an array of length 0 if the method/constructor declares no
813      * exceptions.
814      *
815      * @return an array of objects representing the declared
816      * exceptions of the method or constructor represented by this {@code
817      * Executable}
818      */
819     public AnnotatedType[] getAnnotatedExceptionTypes() {
820         return TypeAnnotationParser.buildAnnotatedTypes(getTypeAnnotationBytes0(),
821                 SharedSecrets.getJavaLangAccess().
822                         getConstantPool(getDeclaringClass()),
823                 this,
824                 getDeclaringClass(),
825                 getGenericExceptionTypes(),
826                 TypeAnnotation.TypeAnnotationTarget.THROWS);
827     }
828 }