View Javadoc
1   /*
2    * Copyright (c) 2012, 2013, 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.*;
29  import java.util.Map;
30  import java.util.Objects;
31  import sun.reflect.annotation.AnnotationParser;
32  import sun.reflect.annotation.AnnotationSupport;
33  import sun.reflect.annotation.TypeAnnotationParser;
34  import sun.reflect.annotation.TypeAnnotation;
35  import sun.reflect.generics.repository.ConstructorRepository;
36  
37  /**
38   * A shared superclass for the common functionality of {@link Method}
39   * and {@link Constructor}.
40   *
41   * @since 1.8
42   */
43  public abstract class Executable extends AccessibleObject
44      implements Member, GenericDeclaration {
45      /*
46       * Only grant package-visibility to the constructor.
47       */
48      Executable() {}
49  
50      /**
51       * Accessor method to allow code sharing
52       */
53      abstract byte[] getAnnotationBytes();
54  
55      /**
56       * Does the Executable have generic information.
57       */
58      abstract boolean hasGenericInformation();
59  
60      abstract ConstructorRepository getGenericInfo();
61  
62      boolean equalParamTypes(Class<?>[] params1, Class<?>[] params2) {
63          /* Avoid unnecessary cloning */
64          if (params1.length == params2.length) {
65              for (int i = 0; i < params1.length; i++) {
66                  if (params1[i] != params2[i])
67                      return false;
68              }
69              return true;
70          }
71          return false;
72      }
73  
74      Annotation[][] parseParameterAnnotations(byte[] parameterAnnotations) {
75          return AnnotationParser.parseParameterAnnotations(
76                 parameterAnnotations,
77                 sun.misc.SharedSecrets.getJavaLangAccess().
78                 getConstantPool(getDeclaringClass()),
79                 getDeclaringClass());
80      }
81  
82      void separateWithCommas(Class<?>[] types, StringBuilder sb) {
83          for (int j = 0; j < types.length; j++) {
84              sb.append(types[j].getTypeName());
85              if (j < (types.length - 1))
86                  sb.append(",");
87          }
88  
89      }
90  
91      void printModifiersIfNonzero(StringBuilder sb, int mask, boolean isDefault) {
92          int mod = getModifiers() & mask;
93  
94          if (mod != 0 && !isDefault) {
95              sb.append(Modifier.toString(mod)).append(' ');
96          } else {
97              int access_mod = mod & Modifier.ACCESS_MODIFIERS;
98              if (access_mod != 0)
99                  sb.append(Modifier.toString(access_mod)).append(' ');
100             if (isDefault)
101                 sb.append("default ");
102             mod = (mod & ~Modifier.ACCESS_MODIFIERS);
103             if (mod != 0)
104                 sb.append(Modifier.toString(mod)).append(' ');
105         }
106     }
107 
108     String sharedToString(int modifierMask,
109                           boolean isDefault,
110                           Class<?>[] parameterTypes,
111                           Class<?>[] exceptionTypes) {
112         try {
113             StringBuilder sb = new StringBuilder();
114 
115             printModifiersIfNonzero(sb, modifierMask, isDefault);
116             specificToStringHeader(sb);
117 
118             sb.append('(');
119             separateWithCommas(parameterTypes, sb);
120             sb.append(')');
121             if (exceptionTypes.length > 0) {
122                 sb.append(" throws ");
123                 separateWithCommas(exceptionTypes, sb);
124             }
125             return sb.toString();
126         } catch (Exception e) {
127             return "<" + e + ">";
128         }
129     }
130 
131     /**
132      * Generate toString header information specific to a method or
133      * constructor.
134      */
135     abstract void specificToStringHeader(StringBuilder sb);
136 
137     String sharedToGenericString(int modifierMask, boolean isDefault) {
138         try {
139             StringBuilder sb = new StringBuilder();
140 
141             printModifiersIfNonzero(sb, modifierMask, isDefault);
142 
143             TypeVariable<?>[] typeparms = getTypeParameters();
144             if (typeparms.length > 0) {
145                 boolean first = true;
146                 sb.append('<');
147                 for(TypeVariable<?> typeparm: typeparms) {
148                     if (!first)
149                         sb.append(',');
150                     // Class objects can't occur here; no need to test
151                     // and call Class.getName().
152                     sb.append(typeparm.toString());
153                     first = false;
154                 }
155                 sb.append("> ");
156             }
157 
158             specificToGenericStringHeader(sb);
159 
160             sb.append('(');
161             Type[] params = getGenericParameterTypes();
162             for (int j = 0; j < params.length; j++) {
163                 String param = params[j].getTypeName();
164                 if (isVarArgs() && (j == params.length - 1)) // replace T[] with T...
165                     param = param.replaceFirst("\\[\\]$", "...");
166                 sb.append(param);
167                 if (j < (params.length - 1))
168                     sb.append(',');
169             }
170             sb.append(')');
171             Type[] exceptions = getGenericExceptionTypes();
172             if (exceptions.length > 0) {
173                 sb.append(" throws ");
174                 for (int k = 0; k < exceptions.length; k++) {
175                     sb.append((exceptions[k] instanceof Class)?
176                               ((Class)exceptions[k]).getName():
177                               exceptions[k].toString());
178                     if (k < (exceptions.length - 1))
179                         sb.append(',');
180                 }
181             }
182             return sb.toString();
183         } catch (Exception e) {
184             return "<" + e + ">";
185         }
186     }
187 
188     /**
189      * Generate toGenericString header information specific to a
190      * method or constructor.
191      */
192     abstract void specificToGenericStringHeader(StringBuilder sb);
193 
194     /**
195      * Returns the {@code Class} object representing the class or interface
196      * that declares the executable represented by this object.
197      */
198     public abstract Class<?> getDeclaringClass();
199 
200     /**
201      * Returns the name of the executable represented by this object.
202      */
203     public abstract String getName();
204 
205     /**
206      * Returns the Java language {@linkplain Modifier modifiers} for
207      * the executable represented by this object.
208      */
209     public abstract int getModifiers();
210 
211     /**
212      * Returns an array of {@code TypeVariable} objects that represent the
213      * type variables declared by the generic declaration represented by this
214      * {@code GenericDeclaration} object, in declaration order.  Returns an
215      * array of length 0 if the underlying generic declaration declares no type
216      * variables.
217      *
218      * @return an array of {@code TypeVariable} objects that represent
219      *     the type variables declared by this generic declaration
220      * @throws GenericSignatureFormatError if the generic
221      *     signature of this generic declaration does not conform to
222      *     the format specified in
223      *     <cite>The Java&trade; Virtual Machine Specification</cite>
224      */
225     public abstract TypeVariable<?>[] getTypeParameters();
226 
227     /**
228      * Returns an array of {@code Class} objects that represent the formal
229      * parameter types, in declaration order, of the executable
230      * represented by this object.  Returns an array of length
231      * 0 if the underlying executable takes no parameters.
232      *
233      * @return the parameter types for the executable this object
234      * represents
235      */
236     public abstract Class<?>[] getParameterTypes();
237 
238     /**
239      * Returns the number of formal parameters (whether explicitly
240      * declared or implicitly declared or neither) for the executable
241      * represented by this object.
242      *
243      * @since 1.8
244      * @return The number of formal parameters for the executable this
245      * object represents
246      */
247     public int getParameterCount() {
248         throw new AbstractMethodError();
249     }
250 
251     /**
252      * Returns an array of {@code Type} objects that represent the formal
253      * parameter types, in declaration order, of the executable represented by
254      * this object. Returns an array of length 0 if the
255      * underlying executable takes no parameters.
256      *
257      * <p>If a formal parameter type is a parameterized type,
258      * the {@code Type} object returned for it must accurately reflect
259      * the actual type parameters used in the source code.
260      *
261      * <p>If a formal parameter type is a type variable or a parameterized
262      * type, it is created. Otherwise, it is resolved.
263      *
264      * @return an array of {@code Type}s that represent the formal
265      *     parameter types of the underlying executable, in declaration order
266      * @throws GenericSignatureFormatError
267      *     if the generic method signature does not conform to the format
268      *     specified in
269      *     <cite>The Java&trade; Virtual Machine Specification</cite>
270      * @throws TypeNotPresentException if any of the parameter
271      *     types of the underlying executable refers to a non-existent type
272      *     declaration
273      * @throws MalformedParameterizedTypeException if any of
274      *     the underlying executable's parameter types refer to a parameterized
275      *     type that cannot be instantiated for any reason
276      */
277     public Type[] getGenericParameterTypes() {
278         if (hasGenericInformation())
279             return getGenericInfo().getParameterTypes();
280         else
281             return getParameterTypes();
282     }
283 
284     /**
285      * Returns an array of {@code Parameter} objects that represent
286      * all the parameters to the underlying executable represented by
287      * this object.  Returns an array of length 0 if the executable
288      * has no parameters.
289      *
290      * <p>The parameters of the underlying executable do not necessarily
291      * have unique names, or names that are legal identifiers in the
292      * Java programming language (JLS 3.8).
293      *
294      * @since 1.8
295      * @throws MalformedParametersException if the class file contains
296      * a MethodParameters attribute that is improperly formatted.
297      * @return an array of {@code Parameter} objects representing all
298      * the parameters to the executable this object represents.
299      */
300     public Parameter[] getParameters() {
301         // TODO: This may eventually need to be guarded by security
302         // mechanisms similar to those in Field, Method, etc.
303         //
304         // Need to copy the cached array to prevent users from messing
305         // with it.  Since parameters are immutable, we can
306         // shallow-copy.
307         return privateGetParameters().clone();
308     }
309 
310     private Parameter[] synthesizeAllParams() {
311         final int realparams = getParameterCount();
312         final Parameter[] out = new Parameter[realparams];
313         for (int i = 0; i < realparams; i++)
314             // TODO: is there a way to synthetically derive the
315             // modifiers?  Probably not in the general case, since
316             // we'd have no way of knowing about them, but there
317             // may be specific cases.
318             out[i] = new Parameter("arg" + i, 0, this, i);
319         return out;
320     }
321 
322     private void verifyParameters(final Parameter[] parameters) {
323         final int mask = Modifier.FINAL | Modifier.SYNTHETIC | Modifier.MANDATED;
324 
325         if (getParameterTypes().length != parameters.length)
326             throw new MalformedParametersException("Wrong number of parameters in MethodParameters attribute");
327 
328         for (Parameter parameter : parameters) {
329             final String name = parameter.getRealName();
330             final int mods = parameter.getModifiers();
331 
332             if (name != null) {
333                 if (name.isEmpty() || name.indexOf('.') != -1 ||
334                     name.indexOf(';') != -1 || name.indexOf('[') != -1 ||
335                     name.indexOf('/') != -1) {
336                     throw new MalformedParametersException("Invalid parameter name \"" + name + "\"");
337                 }
338             }
339 
340             if (mods != (mods & mask)) {
341                 throw new MalformedParametersException("Invalid parameter modifiers");
342             }
343         }
344     }
345 
346     private Parameter[] privateGetParameters() {
347         // Use tmp to avoid multiple writes to a volatile.
348         Parameter[] tmp = parameters;
349 
350         if (tmp == null) {
351 
352             // Otherwise, go to the JVM to get them
353             try {
354                 tmp = getParameters0();
355             } catch(IllegalArgumentException e) {
356                 // Rethrow ClassFormatErrors
357                 throw new MalformedParametersException("Invalid constant pool index");
358             }
359 
360             // If we get back nothing, then synthesize parameters
361             if (tmp == null) {
362                 hasRealParameterData = false;
363                 tmp = synthesizeAllParams();
364             } else {
365                 hasRealParameterData = true;
366                 verifyParameters(tmp);
367             }
368 
369             parameters = tmp;
370         }
371 
372         return tmp;
373     }
374 
375     boolean hasRealParameterData() {
376         // If this somehow gets called before parameters gets
377         // initialized, force it into existence.
378         if (parameters == null) {
379             privateGetParameters();
380         }
381         return hasRealParameterData;
382     }
383 
384     private transient volatile boolean hasRealParameterData;
385     private transient volatile Parameter[] parameters;
386 
387     private native Parameter[] getParameters0();
388     native byte[] getTypeAnnotationBytes0();
389 
390     // Needed by reflectaccess
391     byte[] getTypeAnnotationBytes() {
392         return getTypeAnnotationBytes0();
393     }
394 
395     /**
396      * Returns an array of {@code Class} objects that represent the
397      * types of exceptions declared to be thrown by the underlying
398      * executable represented by this object.  Returns an array of
399      * length 0 if the executable declares no exceptions in its {@code
400      * throws} clause.
401      *
402      * @return the exception types declared as being thrown by the
403      * executable this object represents
404      */
405     public abstract Class<?>[] getExceptionTypes();
406 
407     /**
408      * Returns an array of {@code Type} objects that represent the
409      * exceptions declared to be thrown by this executable object.
410      * Returns an array of length 0 if the underlying executable declares
411      * no exceptions in its {@code throws} clause.
412      *
413      * <p>If an exception type is a type variable or a parameterized
414      * type, it is created. Otherwise, it is resolved.
415      *
416      * @return an array of Types that represent the exception types
417      *     thrown by the underlying executable
418      * @throws GenericSignatureFormatError
419      *     if the generic method signature does not conform to the format
420      *     specified in
421      *     <cite>The Java&trade; Virtual Machine Specification</cite>
422      * @throws TypeNotPresentException if the underlying executable's
423      *     {@code throws} clause refers to a non-existent type declaration
424      * @throws MalformedParameterizedTypeException if
425      *     the underlying executable's {@code throws} clause refers to a
426      *     parameterized type that cannot be instantiated for any reason
427      */
428     public Type[] getGenericExceptionTypes() {
429         Type[] result;
430         if (hasGenericInformation() &&
431             ((result = getGenericInfo().getExceptionTypes()).length > 0))
432             return result;
433         else
434             return getExceptionTypes();
435     }
436 
437     /**
438      * Returns a string describing this {@code Executable}, including
439      * any type parameters.
440      * @return a string describing this {@code Executable}, including
441      * any type parameters
442      */
443     public abstract String toGenericString();
444 
445     /**
446      * Returns {@code true} if this executable was declared to take a
447      * variable number of arguments; returns {@code false} otherwise.
448      *
449      * @return {@code true} if an only if this executable was declared
450      * to take a variable number of arguments.
451      */
452     public boolean isVarArgs()  {
453         return (getModifiers() & Modifier.VARARGS) != 0;
454     }
455 
456     /**
457      * Returns {@code true} if this executable is a synthetic
458      * construct; returns {@code false} otherwise.
459      *
460      * @return true if and only if this executable is a synthetic
461      * construct as defined by
462      * <cite>The Java&trade; Language Specification</cite>.
463      * @jls 13.1 The Form of a Binary
464      */
465     public boolean isSynthetic() {
466         return Modifier.isSynthetic(getModifiers());
467     }
468 
469     /**
470      * Returns an array of arrays of {@code Annotation}s that
471      * represent the annotations on the formal parameters, in
472      * declaration order, of the {@code Executable} represented by
473      * this object.  Synthetic and mandated parameters (see
474      * explanation below), such as the outer "this" parameter to an
475      * inner class constructor will be represented in the returned
476      * array.  If the executable has no parameters (meaning no formal,
477      * no synthetic, and no mandated parameters), a zero-length array
478      * will be returned.  If the {@code Executable} has one or more
479      * parameters, a nested array of length zero is returned for each
480      * parameter with no annotations. The annotation objects contained
481      * in the returned arrays are serializable.  The caller of this
482      * method is free to modify the returned arrays; it will have no
483      * effect on the arrays returned to other callers.
484      *
485      * A compiler may add extra parameters that are implicitly
486      * declared in source ("mandated"), as well as parameters that
487      * are neither implicitly nor explicitly declared in source
488      * ("synthetic") to the parameter list for a method.  See {@link
489      * java.lang.reflect.Parameter} for more information.
490      *
491      * @see java.lang.reflect.Parameter
492      * @see java.lang.reflect.Parameter#getAnnotations
493      * @return an array of arrays that represent the annotations on
494      *    the formal and implicit parameters, in declaration order, of
495      *    the executable represented by this object
496      */
497     public abstract Annotation[][] getParameterAnnotations();
498 
499     Annotation[][] sharedGetParameterAnnotations(Class<?>[] parameterTypes,
500                                                  byte[] parameterAnnotations) {
501         int numParameters = parameterTypes.length;
502         if (parameterAnnotations == null)
503             return new Annotation[numParameters][0];
504 
505         Annotation[][] result = parseParameterAnnotations(parameterAnnotations);
506 
507         if (result.length != numParameters)
508             handleParameterNumberMismatch(result.length, numParameters);
509         return result;
510     }
511 
512     abstract void handleParameterNumberMismatch(int resultLength, int numParameters);
513 
514     /**
515      * {@inheritDoc}
516      * @throws NullPointerException  {@inheritDoc}
517      */
518     public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
519         Objects.requireNonNull(annotationClass);
520         return annotationClass.cast(declaredAnnotations().get(annotationClass));
521     }
522 
523     /**
524      * {@inheritDoc}
525      * @throws NullPointerException {@inheritDoc}
526      * @since 1.8
527      */
528     @Override
529     public <T extends Annotation> T[] getAnnotationsByType(Class<T> annotationClass) {
530         Objects.requireNonNull(annotationClass);
531 
532         return AnnotationSupport.getDirectlyAndIndirectlyPresent(declaredAnnotations(), annotationClass);
533     }
534 
535     /**
536      * {@inheritDoc}
537      */
538     public Annotation[] getDeclaredAnnotations()  {
539         return AnnotationParser.toArray(declaredAnnotations());
540     }
541 
542     private transient Map<Class<? extends Annotation>, Annotation> declaredAnnotations;
543 
544     private synchronized  Map<Class<? extends Annotation>, Annotation> declaredAnnotations() {
545         if (declaredAnnotations == null) {
546             declaredAnnotations = AnnotationParser.parseAnnotations(
547                 getAnnotationBytes(),
548                 sun.misc.SharedSecrets.getJavaLangAccess().
549                 getConstantPool(getDeclaringClass()),
550                 getDeclaringClass());
551         }
552         return declaredAnnotations;
553     }
554 
555     /**
556      * Returns an {@code AnnotatedType} object that represents the use of a type to
557      * specify the return type of the method/constructor represented by this
558      * Executable.
559      *
560      * If this {@code Executable} object represents a constructor, the {@code
561      * AnnotatedType} object represents the type of the constructed object.
562      *
563      * If this {@code Executable} object represents a method, the {@code
564      * AnnotatedType} object represents the use of a type to specify the return
565      * type of the method.
566      *
567      * @return an object representing the return type of the method
568      * or constructor represented by this {@code Executable}
569      *
570      * @since 1.8
571      */
572     public abstract AnnotatedType getAnnotatedReturnType();
573 
574     /* Helper for subclasses of Executable.
575      *
576      * Returns an AnnotatedType object that represents the use of a type to
577      * specify the return type of the method/constructor represented by this
578      * Executable.
579      *
580      * @since 1.8
581      */
582     AnnotatedType getAnnotatedReturnType0(Type returnType) {
583         return TypeAnnotationParser.buildAnnotatedType(getTypeAnnotationBytes0(),
584                 sun.misc.SharedSecrets.getJavaLangAccess().
585                         getConstantPool(getDeclaringClass()),
586                 this,
587                 getDeclaringClass(),
588                 returnType,
589                 TypeAnnotation.TypeAnnotationTarget.METHOD_RETURN);
590     }
591 
592     /**
593      * Returns an {@code AnnotatedType} object that represents the use of a
594      * type to specify the receiver type of the method/constructor represented
595      * by this Executable object. The receiver type of a method/constructor is
596      * available only if the method/constructor has a <em>receiver
597      * parameter</em> (JLS 8.4.1).
598      *
599      * If this {@code Executable} object represents a constructor or instance
600      * method that does not have a receiver parameter, or has a receiver
601      * parameter with no annotations on its type, then the return value is an
602      * {@code AnnotatedType} object representing an element with no
603      * annotations.
604      *
605      * If this {@code Executable} object represents a static method, then the
606      * return value is null.
607      *
608      * @return an object representing the receiver type of the method or
609      * constructor represented by this {@code Executable}
610      *
611      * @since 1.8
612      */
613     public AnnotatedType getAnnotatedReceiverType() {
614         if (Modifier.isStatic(this.getModifiers()))
615             return null;
616         return TypeAnnotationParser.buildAnnotatedType(getTypeAnnotationBytes0(),
617                 sun.misc.SharedSecrets.getJavaLangAccess().
618                         getConstantPool(getDeclaringClass()),
619                 this,
620                 getDeclaringClass(),
621                 getDeclaringClass(),
622                 TypeAnnotation.TypeAnnotationTarget.METHOD_RECEIVER);
623     }
624 
625     /**
626      * Returns an array of {@code AnnotatedType} objects that represent the use
627      * of types to specify formal parameter types of the method/constructor
628      * represented by this Executable. The order of the objects in the array
629      * corresponds to the order of the formal parameter types in the
630      * declaration of the method/constructor.
631      *
632      * Returns an array of length 0 if the method/constructor declares no
633      * parameters.
634      *
635      * @return an array of objects representing the types of the
636      * formal parameters of the method or constructor represented by this
637      * {@code Executable}
638      *
639      * @since 1.8
640      */
641     public AnnotatedType[] getAnnotatedParameterTypes() {
642         return TypeAnnotationParser.buildAnnotatedTypes(getTypeAnnotationBytes0(),
643                 sun.misc.SharedSecrets.getJavaLangAccess().
644                         getConstantPool(getDeclaringClass()),
645                 this,
646                 getDeclaringClass(),
647                 getParameterTypes(),
648                 TypeAnnotation.TypeAnnotationTarget.METHOD_FORMAL_PARAMETER);
649     }
650 
651     /**
652      * Returns an array of {@code AnnotatedType} objects that represent the use
653      * of types to specify the declared exceptions of the method/constructor
654      * represented by this Executable. The order of the objects in the array
655      * corresponds to the order of the exception types in the declaration of
656      * the method/constructor.
657      *
658      * Returns an array of length 0 if the method/constructor declares no
659      * exceptions.
660      *
661      * @return an array of objects representing the declared
662      * exceptions of the method or constructor represented by this {@code
663      * Executable}
664      *
665      * @since 1.8
666      */
667     public AnnotatedType[] getAnnotatedExceptionTypes() {
668         return TypeAnnotationParser.buildAnnotatedTypes(getTypeAnnotationBytes0(),
669                 sun.misc.SharedSecrets.getJavaLangAccess().
670                         getConstantPool(getDeclaringClass()),
671                 this,
672                 getDeclaringClass(),
673                 getGenericExceptionTypes(),
674                 TypeAnnotation.TypeAnnotationTarget.THROWS);
675     }
676 
677 }