1 /*
   2  * Copyright (c) 2012, 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.Collections;
  30 import java.util.Map;
  31 import java.util.Objects;
  32 import sun.reflect.annotation.AnnotationParser;
  33 import sun.reflect.annotation.AnnotationSupport;
  34 import sun.reflect.generics.repository.ConstructorRepository;
  35 
  36 /**
  37  * A shared superclass for the common functionality of {@link Method}
  38  * and {@link Constructor}.
  39  *
  40  * @since 1.8
  41  */
  42 public abstract class Executable extends AccessibleObject
  43     implements Member, GenericDeclaration {
  44     /*
  45      * Only grant package-visibility to the constructor.
  46      */
  47     Executable() {}
  48 
  49     /**
  50      * Accessor method to allow code sharing
  51      */
  52     abstract byte[] getAnnotationBytes();
  53 
  54     /**
  55      * Does the Executable have generic information.
  56      */
  57     abstract boolean hasGenericInformation();
  58 
  59     abstract ConstructorRepository getGenericInfo();
  60 
  61     boolean equalParamTypes(Class<?>[] params1, Class<?>[] params2) {
  62         /* Avoid unnecessary cloning */
  63         if (params1.length == params2.length) {
  64             for (int i = 0; i < params1.length; i++) {
  65                 if (params1[i] != params2[i])
  66                     return false;
  67             }
  68             return true;
  69         }
  70         return false;
  71     }
  72 
  73     Annotation[][] parseParameterAnnotations(byte[] parameterAnnotations) {
  74         return AnnotationParser.parseParameterAnnotations(
  75                parameterAnnotations,
  76                sun.misc.SharedSecrets.getJavaLangAccess().
  77                getConstantPool(getDeclaringClass()),
  78                getDeclaringClass());
  79     }
  80 
  81     void separateWithCommas(Class<?>[] types, StringBuilder sb) {
  82         for (int j = 0; j < types.length; j++) {
  83             sb.append(Field.getTypeName(types[j]));
  84             if (j < (types.length - 1))
  85                 sb.append(",");
  86         }
  87 
  88     }
  89 
  90     void printModifiersIfNonzero(StringBuilder sb, int mask) {
  91         int mod = getModifiers() & mask;
  92         if (mod != 0) {
  93             sb.append(Modifier.toString(mod)).append(' ');
  94         }
  95     }
  96 
  97     String sharedToString(int modifierMask,
  98                           Class<?>[] parameterTypes,
  99                           Class<?>[] exceptionTypes) {
 100         try {
 101             StringBuilder sb = new StringBuilder();
 102 
 103             printModifiersIfNonzero(sb, modifierMask);
 104             specificToStringHeader(sb);
 105 
 106             sb.append('(');
 107             separateWithCommas(parameterTypes, sb);
 108             sb.append(')');
 109             if (exceptionTypes.length > 0) {
 110                 sb.append(" throws ");
 111                 separateWithCommas(exceptionTypes, sb);
 112             }
 113             return sb.toString();
 114         } catch (Exception e) {
 115             return "<" + e + ">";
 116         }
 117     }
 118 
 119     /**
 120      * Generate toString header information specific to a method or
 121      * constructor.
 122      */
 123     abstract void specificToStringHeader(StringBuilder sb);
 124 
 125     String sharedToGenericString(int modifierMask) {
 126         try {
 127             StringBuilder sb = new StringBuilder();
 128 
 129             printModifiersIfNonzero(sb, modifierMask);
 130 
 131             TypeVariable<?>[] typeparms = getTypeParameters();
 132             if (typeparms.length > 0) {
 133                 boolean first = true;
 134                 sb.append('<');
 135                 for(TypeVariable<?> typeparm: typeparms) {
 136                     if (!first)
 137                         sb.append(',');
 138                     // Class objects can't occur here; no need to test
 139                     // and call Class.getName().
 140                     sb.append(typeparm.toString());
 141                     first = false;
 142                 }
 143                 sb.append("> ");
 144             }
 145 
 146             specificToGenericStringHeader(sb);
 147 
 148             sb.append('(');
 149             Type[] params = getGenericParameterTypes();
 150             for (int j = 0; j < params.length; j++) {
 151                 String param = (params[j] instanceof Class)?
 152                     Field.getTypeName((Class)params[j]):
 153                     (params[j].toString());
 154                 if (isVarArgs() && (j == params.length - 1)) // replace T[] with T...
 155                     param = param.replaceFirst("\\[\\]$", "...");
 156                 sb.append(param);
 157                 if (j < (params.length - 1))
 158                     sb.append(',');
 159             }
 160             sb.append(')');
 161             Type[] exceptions = getGenericExceptionTypes();
 162             if (exceptions.length > 0) {
 163                 sb.append(" throws ");
 164                 for (int k = 0; k < exceptions.length; k++) {
 165                     sb.append((exceptions[k] instanceof Class)?
 166                               ((Class)exceptions[k]).getName():
 167                               exceptions[k].toString());
 168                     if (k < (exceptions.length - 1))
 169                         sb.append(',');
 170                 }
 171             }
 172             return sb.toString();
 173         } catch (Exception e) {
 174             return "<" + e + ">";
 175         }
 176     }
 177 
 178     /**
 179      * Generate toGenericString header information specific to a
 180      * method or constructor.
 181      */
 182     abstract void specificToGenericStringHeader(StringBuilder sb);
 183 
 184     /**
 185      * Returns the {@code Class} object representing the class or interface
 186      * that declares the executable represented by this object.
 187      */
 188     public abstract Class<?> getDeclaringClass();
 189 
 190     /**
 191      * Returns the name of the executable represented by this object.
 192      */
 193     public abstract String getName();
 194 
 195     /**
 196      * Returns the Java language {@linkplain Modifier modifiers} for
 197      * the executable represented by this object.
 198      */
 199     public abstract int getModifiers();
 200 
 201     /**
 202      * Returns an array of {@code TypeVariable} objects that represent the
 203      * type variables declared by the generic declaration represented by this
 204      * {@code GenericDeclaration} object, in declaration order.  Returns an
 205      * array of length 0 if the underlying generic declaration declares no type
 206      * variables.
 207      *
 208      * @return an array of {@code TypeVariable} objects that represent
 209      *     the type variables declared by this generic declaration
 210      * @throws GenericSignatureFormatError if the generic
 211      *     signature of this generic declaration does not conform to
 212      *     the format specified in
 213      *     <cite>The Java&trade; Virtual Machine Specification</cite>
 214      */
 215     public abstract TypeVariable<?>[] getTypeParameters();
 216 
 217     /**
 218      * Returns an array of {@code Class} objects that represent the formal
 219      * parameter types, in declaration order, of the executable
 220      * represented by this object.  Returns an array of length
 221      * 0 if the underlying executable takes no parameters.
 222      *
 223      * @return the parameter types for the executable this object
 224      * represents
 225      */
 226     public abstract Class<?>[] getParameterTypes();
 227 
 228     /**
 229      * Returns an array of {@code Type} objects that represent the formal
 230      * parameter types, in declaration order, of the executable represented by
 231      * this object. Returns an array of length 0 if the
 232      * underlying executable takes no parameters.
 233      *
 234      * <p>If a formal parameter type is a parameterized type,
 235      * the {@code Type} object returned for it must accurately reflect
 236      * the actual type parameters used in the source code.
 237      *
 238      * <p>If a formal parameter type is a type variable or a parameterized
 239      * type, it is created. Otherwise, it is resolved.
 240      *
 241      * @return an array of {@code Type}s that represent the formal
 242      *     parameter types of the underlying executable, in declaration order
 243      * @throws GenericSignatureFormatError
 244      *     if the generic method signature does not conform to the format
 245      *     specified in
 246      *     <cite>The Java&trade; Virtual Machine Specification</cite>
 247      * @throws TypeNotPresentException if any of the parameter
 248      *     types of the underlying executable refers to a non-existent type
 249      *     declaration
 250      * @throws MalformedParameterizedTypeException if any of
 251      *     the underlying executable's parameter types refer to a parameterized
 252      *     type that cannot be instantiated for any reason
 253      */
 254     public Type[] getGenericParameterTypes() {
 255         if (hasGenericInformation())
 256             return getGenericInfo().getParameterTypes();
 257         else
 258             return getParameterTypes();
 259     }
 260 
 261     /**
 262      * Returns an array of {@code Class} objects that represent the
 263      * types of exceptions declared to be thrown by the underlying
 264      * executable represented by this object.  Returns an array of
 265      * length 0 if the executable declares no exceptions in its {@code
 266      * throws} clause.
 267      *
 268      * @return the exception types declared as being thrown by the
 269      * executable this object represents
 270      */
 271     public abstract Class<?>[] getExceptionTypes();
 272 
 273     /**
 274      * Returns an array of {@code Type} objects that represent the
 275      * exceptions declared to be thrown by this executable object.
 276      * Returns an array of length 0 if the underlying executable declares
 277      * no exceptions in its {@code throws} clause.
 278      *
 279      * <p>If an exception type is a type variable or a parameterized
 280      * type, it is created. Otherwise, it is resolved.
 281      *
 282      * @return an array of Types that represent the exception types
 283      *     thrown by the underlying executable
 284      * @throws GenericSignatureFormatError
 285      *     if the generic method signature does not conform to the format
 286      *     specified in
 287      *     <cite>The Java&trade; Virtual Machine Specification</cite>
 288      * @throws TypeNotPresentException if the underlying executable's
 289      *     {@code throws} clause refers to a non-existent type declaration
 290      * @throws MalformedParameterizedTypeException if
 291      *     the underlying executable's {@code throws} clause refers to a
 292      *     parameterized type that cannot be instantiated for any reason
 293      */
 294     public Type[] getGenericExceptionTypes() {
 295         Type[] result;
 296         if (hasGenericInformation() &&
 297             ((result = getGenericInfo().getExceptionTypes()).length > 0))
 298             return result;
 299         else
 300             return getExceptionTypes();
 301     }
 302 
 303     /**
 304      * Returns a string describing this {@code Executable}, including
 305      * any type parameters.
 306      */
 307     public abstract String toGenericString();
 308 
 309     /**
 310      * Returns {@code true} if this executable was declared to take a
 311      * variable number of arguments; returns {@code false} otherwise.
 312      *
 313      * @return {@code true} if an only if this executable was declared
 314      * to take a variable number of arguments.
 315      */
 316     public boolean isVarArgs()  {
 317         return (getModifiers() & Modifier.VARARGS) != 0;
 318     }
 319 
 320     /**
 321      * Returns {@code true} if this executable is a synthetic
 322      * construct; returns {@code false} otherwise.
 323      *
 324      * @return true if and only if this executable is a synthetic
 325      * construct as defined by
 326      * <cite>The Java&trade; Language Specification</cite>.
 327      * @jls 13.1 The Form of a Binary
 328      */
 329     public boolean isSynthetic() {
 330         return Modifier.isSynthetic(getModifiers());
 331     }
 332 
 333     /**
 334      * Returns an array of arrays that represent the annotations on
 335      * the formal parameters, in declaration order, of the executable
 336      * represented by this object. (Returns an array of length zero if
 337      * the underlying executable is parameterless.  If the executable has
 338      * one or more parameters, a nested array of length zero is
 339      * returned for each parameter with no annotations.) The
 340      * annotation objects contained in the returned arrays are
 341      * serializable.  The caller of this method is free to modify the
 342      * returned arrays; it will have no effect on the arrays returned
 343      * to other callers.
 344      *
 345      * @return an array of arrays that represent the annotations on the formal
 346      *    parameters, in declaration order, of the executable represented by this
 347      *    object
 348      */
 349     public abstract Annotation[][] getParameterAnnotations();
 350 
 351     Annotation[][] sharedGetParameterAnnotations(Class<?>[] parameterTypes,
 352                                                  byte[] parameterAnnotations) {
 353         int numParameters = parameterTypes.length;
 354         if (parameterAnnotations == null)
 355             return new Annotation[numParameters][0];
 356 
 357         Annotation[][] result = parseParameterAnnotations(parameterAnnotations);
 358 
 359         if (result.length != numParameters)
 360             handleParameterNumberMismatch(result.length, numParameters);
 361         return result;
 362     }
 363 
 364     abstract void handleParameterNumberMismatch(int resultLength, int numParameters);
 365 
 366     /**
 367      * {@inheritDoc}
 368      * @throws NullPointerException  {@inheritDoc}
 369      */
 370     public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
 371         Objects.requireNonNull(annotationClass);
 372 
 373         return AnnotationSupport.getOneAnnotation(declaredAnnotations(), annotationClass);
 374     }
 375 
 376     /**
 377      * {@inheritDoc}
 378      * @throws NullPointerException {@inheritDoc}
 379      * @since 1.8
 380      */
 381     public <T extends Annotation> T[] getAnnotations(Class<T> annotationClass) {
 382         Objects.requireNonNull(annotationClass);
 383 
 384         return AnnotationSupport.getMultipleAnnotations(declaredAnnotations(), annotationClass);
 385     }
 386 
 387     /**
 388      * {@inheritDoc}
 389      */
 390     public Annotation[] getDeclaredAnnotations()  {
 391         return AnnotationSupport.unpackToArray(declaredAnnotations());
 392     }
 393 
 394     private transient Map<Class<? extends Annotation>, Annotation> declaredAnnotations;
 395 
 396     private synchronized  Map<Class<? extends Annotation>, Annotation> declaredAnnotations() {
 397         if (declaredAnnotations == null) {
 398             declaredAnnotations = AnnotationParser.parseAnnotations(
 399                 getAnnotationBytes(),
 400                 sun.misc.SharedSecrets.getJavaLangAccess().
 401                 getConstantPool(getDeclaringClass()),
 402                 getDeclaringClass());
 403         }
 404         return declaredAnnotations;
 405     }
 406 }