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 the number of formal parameters (including any
 230      * synthetic or synthesized parameters) for the executable
 231      * represented by this object.
 232      *
 233      * @return The number of formal parameters for the executable this
 234      * object represents
 235      */
 236     public int getParameterCount() {
 237         throw new AbstractMethodError();
 238     }
 239 
 240     /**
 241      * Returns an array of {@code Type} objects that represent the formal
 242      * parameter types, in declaration order, of the executable represented by
 243      * this object. Returns an array of length 0 if the
 244      * underlying executable takes no parameters.
 245      *
 246      * <p>If a formal parameter type is a parameterized type,
 247      * the {@code Type} object returned for it must accurately reflect
 248      * the actual type parameters used in the source code.
 249      *
 250      * <p>If a formal parameter type is a type variable or a parameterized
 251      * type, it is created. Otherwise, it is resolved.
 252      *
 253      * @return an array of {@code Type}s that represent the formal
 254      *     parameter types of the underlying executable, in declaration order
 255      * @throws GenericSignatureFormatError
 256      *     if the generic method signature does not conform to the format
 257      *     specified in
 258      *     <cite>The Java&trade; Virtual Machine Specification</cite>
 259      * @throws TypeNotPresentException if any of the parameter
 260      *     types of the underlying executable refers to a non-existent type
 261      *     declaration
 262      * @throws MalformedParameterizedTypeException if any of
 263      *     the underlying executable's parameter types refer to a parameterized
 264      *     type that cannot be instantiated for any reason
 265      */
 266     public Type[] getGenericParameterTypes() {
 267         if (hasGenericInformation())
 268             return getGenericInfo().getParameterTypes();
 269         else
 270             return getParameterTypes();
 271     }
 272 
 273     /**
 274      * Returns an array of {@code Parameter} objects that represent
 275      * all the parameters to the underlying executable represented by
 276      * this object.  Returns an array of length 0 if the executable
 277      * has no parameters.
 278      *
 279      * @return an array of {@code Parameter} objects representing all
 280      * the parameters to the executable this object represents
 281      */
 282     public Parameter[] getParameters() {
 283         // TODO: This may eventually need to be guarded by security
 284         // mechanisms similar to those in Field, Method, etc.
 285         //
 286         // Need to copy the cached array to prevent users from messing
 287         // with it.  Since parameters are immutable, we can
 288         // shallow-copy.
 289         return privateGetParameters().clone();
 290     }
 291 
 292     private Parameter[] synthesizeAllParams() {
 293         final int realparams = getParameterCount();
 294         final Parameter[] out = new Parameter[realparams];
 295         for (int i = 0; i < realparams; i++)
 296             // TODO: is there a way to synthetically derive the
 297             // modifiers?  Probably not in the general case, since
 298             // we'd have no way of knowing about them, but there
 299             // may be specific cases.
 300             out[i] = new Parameter("arg" + i, 0, this, i);
 301         return out;
 302     }
 303 
 304     private Parameter[] privateGetParameters() {
 305         // Use tmp to avoid multiple writes to a volatile.
 306         Parameter[] tmp = parameters;
 307 
 308         if (tmp == null) {
 309 
 310             // Otherwise, go to the JVM to get them
 311             tmp = getParameters0();
 312 
 313             // If we get back nothing, then synthesize parameters
 314             if (tmp == null)
 315                 tmp = synthesizeAllParams();
 316 
 317             parameters = tmp;
 318 
 319         }
 320 
 321         return tmp;
 322     }
 323 
 324     private transient volatile Parameter[] parameters;
 325 
 326     private native Parameter[] getParameters0();
 327 
 328     /**
 329      * Returns an array of {@code Class} objects that represent the
 330      * types of exceptions declared to be thrown by the underlying
 331      * executable represented by this object.  Returns an array of
 332      * length 0 if the executable declares no exceptions in its {@code
 333      * throws} clause.
 334      *
 335      * @return the exception types declared as being thrown by the
 336      * executable this object represents
 337      */
 338     public abstract Class<?>[] getExceptionTypes();
 339 
 340     /**
 341      * Returns an array of {@code Type} objects that represent the
 342      * exceptions declared to be thrown by this executable object.
 343      * Returns an array of length 0 if the underlying executable declares
 344      * no exceptions in its {@code throws} clause.
 345      *
 346      * <p>If an exception type is a type variable or a parameterized
 347      * type, it is created. Otherwise, it is resolved.
 348      *
 349      * @return an array of Types that represent the exception types
 350      *     thrown by the underlying executable
 351      * @throws GenericSignatureFormatError
 352      *     if the generic method signature does not conform to the format
 353      *     specified in
 354      *     <cite>The Java&trade; Virtual Machine Specification</cite>
 355      * @throws TypeNotPresentException if the underlying executable's
 356      *     {@code throws} clause refers to a non-existent type declaration
 357      * @throws MalformedParameterizedTypeException if
 358      *     the underlying executable's {@code throws} clause refers to a
 359      *     parameterized type that cannot be instantiated for any reason
 360      */
 361     public Type[] getGenericExceptionTypes() {
 362         Type[] result;
 363         if (hasGenericInformation() &&
 364             ((result = getGenericInfo().getExceptionTypes()).length > 0))
 365             return result;
 366         else
 367             return getExceptionTypes();
 368     }
 369 
 370     /**
 371      * Returns a string describing this {@code Executable}, including
 372      * any type parameters.
 373      */
 374     public abstract String toGenericString();
 375 
 376     /**
 377      * Returns {@code true} if this executable was declared to take a
 378      * variable number of arguments; returns {@code false} otherwise.
 379      *
 380      * @return {@code true} if an only if this executable was declared
 381      * to take a variable number of arguments.
 382      */
 383     public boolean isVarArgs()  {
 384         return (getModifiers() & Modifier.VARARGS) != 0;
 385     }
 386 
 387     /**
 388      * Returns {@code true} if this executable is a synthetic
 389      * construct; returns {@code false} otherwise.
 390      *
 391      * @return true if and only if this executable is a synthetic
 392      * construct as defined by
 393      * <cite>The Java&trade; Language Specification</cite>.
 394      * @jls 13.1 The Form of a Binary
 395      */
 396     public boolean isSynthetic() {
 397         return Modifier.isSynthetic(getModifiers());
 398     }
 399 
 400     /**
 401      * Returns an array of arrays that represent the annotations on
 402      * the formal parameters, in declaration order, of the executable
 403      * represented by this object. (Returns an array of length zero if
 404      * the underlying executable is parameterless.  If the executable has
 405      * one or more parameters, a nested array of length zero is
 406      * returned for each parameter with no annotations.) The
 407      * annotation objects contained in the returned arrays are
 408      * serializable.  The caller of this method is free to modify the
 409      * returned arrays; it will have no effect on the arrays returned
 410      * to other callers.
 411      *
 412      * @return an array of arrays that represent the annotations on the formal
 413      *    parameters, in declaration order, of the executable represented by this
 414      *    object
 415      */
 416     public abstract Annotation[][] getParameterAnnotations();
 417 
 418     Annotation[][] sharedGetParameterAnnotations(Class<?>[] parameterTypes,
 419                                                  byte[] parameterAnnotations) {
 420         int numParameters = parameterTypes.length;
 421         if (parameterAnnotations == null)
 422             return new Annotation[numParameters][0];
 423 
 424         Annotation[][] result = parseParameterAnnotations(parameterAnnotations);
 425 
 426         if (result.length != numParameters)
 427             handleParameterNumberMismatch(result.length, numParameters);
 428         return result;
 429     }
 430 
 431     abstract void handleParameterNumberMismatch(int resultLength, int numParameters);
 432 
 433     /**
 434      * {@inheritDoc}
 435      * @throws NullPointerException  {@inheritDoc}
 436      */
 437     public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
 438         Objects.requireNonNull(annotationClass);
 439 
 440         return AnnotationSupport.getOneAnnotation(declaredAnnotations(), annotationClass);
 441     }
 442 
 443     /**
 444      * {@inheritDoc}
 445      * @throws NullPointerException {@inheritDoc}
 446      * @since 1.8
 447      */
 448     public <T extends Annotation> T[] getAnnotations(Class<T> annotationClass) {
 449         Objects.requireNonNull(annotationClass);
 450 
 451         return AnnotationSupport.getMultipleAnnotations(declaredAnnotations(), annotationClass);
 452     }
 453 
 454     /**
 455      * {@inheritDoc}
 456      */
 457     public Annotation[] getDeclaredAnnotations()  {
 458         return AnnotationSupport.unpackToArray(declaredAnnotations());
 459     }
 460 
 461     private transient Map<Class<? extends Annotation>, Annotation> declaredAnnotations;
 462 
 463     private synchronized  Map<Class<? extends Annotation>, Annotation> declaredAnnotations() {
 464         if (declaredAnnotations == null) {
 465             declaredAnnotations = AnnotationParser.parseAnnotations(
 466                 getAnnotationBytes(),
 467                 sun.misc.SharedSecrets.getJavaLangAccess().
 468                 getConstantPool(getDeclaringClass()),
 469                 getDeclaringClass());
 470         }
 471         return declaredAnnotations;
 472     }
 473 
 474 }