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