1 /*
   2  * Copyright (c) 1996, 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 jdk.internal.misc.SharedSecrets;
  29 import sun.reflect.CallerSensitive;
  30 import sun.reflect.ConstructorAccessor;
  31 import sun.reflect.Reflection;
  32 import sun.reflect.annotation.TypeAnnotation;
  33 import sun.reflect.annotation.TypeAnnotationParser;
  34 import sun.reflect.generics.repository.ConstructorRepository;
  35 import sun.reflect.generics.factory.CoreReflectionFactory;
  36 import sun.reflect.generics.factory.GenericsFactory;
  37 import sun.reflect.generics.scope.ConstructorScope;
  38 import java.lang.annotation.Annotation;
  39 import java.lang.annotation.AnnotationFormatError;
  40 
  41 /**
  42  * {@code Constructor} provides information about, and access to, a single
  43  * constructor for a class.
  44  *
  45  * <p>{@code Constructor} permits widening conversions to occur when matching the
  46  * actual parameters to newInstance() with the underlying
  47  * constructor's formal parameters, but throws an
  48  * {@code IllegalArgumentException} if a narrowing conversion would occur.
  49  *
  50  * @param <T> the class in which the constructor is declared
  51  *
  52  * @see Member
  53  * @see java.lang.Class
  54  * @see java.lang.Class#getConstructors()
  55  * @see java.lang.Class#getConstructor(Class[])
  56  * @see java.lang.Class#getDeclaredConstructors()
  57  *
  58  * @author      Kenneth Russell
  59  * @author      Nakul Saraiya
  60  */
  61 public final class Constructor<T> extends Executable {
  62     private Class<T>            clazz;
  63     private int                 slot;
  64     private Class<?>[]          parameterTypes;
  65     private Class<?>[]          exceptionTypes;
  66     private int                 modifiers;
  67     // Generics and annotations support
  68     private transient String    signature;
  69     // generic info repository; lazily initialized
  70     private transient ConstructorRepository genericInfo;
  71     private byte[]              annotations;
  72     private byte[]              parameterAnnotations;
  73 
  74     // Generics infrastructure
  75     // Accessor for factory
  76     private GenericsFactory getFactory() {
  77         // create scope and factory
  78         return CoreReflectionFactory.make(this, ConstructorScope.make(this));
  79     }
  80 
  81     // Accessor for generic info repository
  82     @Override
  83     ConstructorRepository getGenericInfo() {
  84         // lazily initialize repository if necessary
  85         if (genericInfo == null) {
  86             // create and cache generic info repository
  87             genericInfo =
  88                 ConstructorRepository.make(getSignature(),
  89                                            getFactory());
  90         }
  91         return genericInfo; //return cached repository
  92     }
  93 
  94     private volatile ConstructorAccessor constructorAccessor;
  95     // For sharing of ConstructorAccessors. This branching structure
  96     // is currently only two levels deep (i.e., one root Constructor
  97     // and potentially many Constructor objects pointing to it.)
  98     //
  99     // If this branching structure would ever contain cycles, deadlocks can
 100     // occur in annotation code.
 101     private Constructor<T>      root;
 102 
 103     /**
 104      * Used by Excecutable for annotation sharing.
 105      */
 106     @Override
 107     Executable getRoot() {
 108         return root;
 109     }
 110 
 111     /**
 112      * Package-private constructor used by ReflectAccess to enable
 113      * instantiation of these objects in Java code from the java.lang
 114      * package via sun.reflect.LangReflectAccess.
 115      */
 116     Constructor(Class<T> declaringClass,
 117                 Class<?>[] parameterTypes,
 118                 Class<?>[] checkedExceptions,
 119                 int modifiers,
 120                 int slot,
 121                 String signature,
 122                 byte[] annotations,
 123                 byte[] parameterAnnotations) {
 124         this.clazz = declaringClass;
 125         this.parameterTypes = parameterTypes;
 126         this.exceptionTypes = checkedExceptions;
 127         this.modifiers = modifiers;
 128         this.slot = slot;
 129         this.signature = signature;
 130         this.annotations = annotations;
 131         this.parameterAnnotations = parameterAnnotations;
 132     }
 133 
 134     /**
 135      * Package-private routine (exposed to java.lang.Class via
 136      * ReflectAccess) which returns a copy of this Constructor. The copy's
 137      * "root" field points to this Constructor.
 138      */
 139     Constructor<T> copy() {
 140         // This routine enables sharing of ConstructorAccessor objects
 141         // among Constructor objects which refer to the same underlying
 142         // method in the VM. (All of this contortion is only necessary
 143         // because of the "accessibility" bit in AccessibleObject,
 144         // which implicitly requires that new java.lang.reflect
 145         // objects be fabricated for each reflective call on Class
 146         // objects.)
 147         if (this.root != null)
 148             throw new IllegalArgumentException("Can not copy a non-root Constructor");
 149 
 150         Constructor<T> res = new Constructor<>(clazz,
 151                                                parameterTypes,
 152                                                exceptionTypes, modifiers, slot,
 153                                                signature,
 154                                                annotations,
 155                                                parameterAnnotations);
 156         res.root = this;
 157         // Might as well eagerly propagate this if already present
 158         res.constructorAccessor = constructorAccessor;
 159         return res;
 160     }
 161 
 162     @Override
 163     boolean hasGenericInformation() {
 164         return (getSignature() != null);
 165     }
 166 
 167     @Override
 168     byte[] getAnnotationBytes() {
 169         return annotations;
 170     }
 171 
 172     /**
 173      * {@inheritDoc}
 174      */
 175     @Override
 176     public Class<T> getDeclaringClass() {
 177         return clazz;
 178     }
 179 
 180     /**
 181      * Returns the name of this constructor, as a string.  This is
 182      * the binary name of the constructor's declaring class.
 183      */
 184     @Override
 185     public String getName() {
 186         return getDeclaringClass().getName();
 187     }
 188 
 189     /**
 190      * {@inheritDoc}
 191      */
 192     @Override
 193     public int getModifiers() {
 194         return modifiers;
 195     }
 196 
 197     /**
 198      * {@inheritDoc}
 199      * @throws GenericSignatureFormatError {@inheritDoc}
 200      * @since 1.5
 201      */
 202     @Override
 203     @SuppressWarnings({"rawtypes", "unchecked"})
 204     public TypeVariable<Constructor<T>>[] getTypeParameters() {
 205       if (getSignature() != null) {
 206         return (TypeVariable<Constructor<T>>[])getGenericInfo().getTypeParameters();
 207       } else
 208           return (TypeVariable<Constructor<T>>[])new TypeVariable[0];
 209     }
 210 
 211 
 212     /**
 213      * {@inheritDoc}
 214      */
 215     @Override
 216     public Class<?>[] getParameterTypes() {
 217         return parameterTypes.clone();
 218     }
 219 
 220     /**
 221      * {@inheritDoc}
 222      * @since 1.8
 223      */
 224     public int getParameterCount() { return parameterTypes.length; }
 225 
 226     /**
 227      * {@inheritDoc}
 228      * @throws GenericSignatureFormatError {@inheritDoc}
 229      * @throws TypeNotPresentException {@inheritDoc}
 230      * @throws MalformedParameterizedTypeException {@inheritDoc}
 231      * @since 1.5
 232      */
 233     @Override
 234     public Type[] getGenericParameterTypes() {
 235         return super.getGenericParameterTypes();
 236     }
 237 
 238     /**
 239      * {@inheritDoc}
 240      */
 241     @Override
 242     public Class<?>[] getExceptionTypes() {
 243         return exceptionTypes.clone();
 244     }
 245 
 246 
 247     /**
 248      * {@inheritDoc}
 249      * @throws GenericSignatureFormatError {@inheritDoc}
 250      * @throws TypeNotPresentException {@inheritDoc}
 251      * @throws MalformedParameterizedTypeException {@inheritDoc}
 252      * @since 1.5
 253      */
 254     @Override
 255     public Type[] getGenericExceptionTypes() {
 256         return super.getGenericExceptionTypes();
 257     }
 258 
 259     /**
 260      * Compares this {@code Constructor} against the specified object.
 261      * Returns true if the objects are the same.  Two {@code Constructor} objects are
 262      * the same if they were declared by the same class and have the
 263      * same formal parameter types.
 264      */
 265     public boolean equals(Object obj) {
 266         if (obj != null && obj instanceof Constructor) {
 267             Constructor<?> other = (Constructor<?>)obj;
 268             if (getDeclaringClass() == other.getDeclaringClass()) {
 269                 return equalParamTypes(parameterTypes, other.parameterTypes);
 270             }
 271         }
 272         return false;
 273     }
 274 
 275     /**
 276      * Returns a hashcode for this {@code Constructor}. The hashcode is
 277      * the same as the hashcode for the underlying constructor's
 278      * declaring class name.
 279      */
 280     public int hashCode() {
 281         return getDeclaringClass().getName().hashCode();
 282     }
 283 
 284     /**
 285      * Returns a string describing this {@code Constructor}.  The string is
 286      * formatted as the constructor access modifiers, if any,
 287      * followed by the fully-qualified name of the declaring class,
 288      * followed by a parenthesized, comma-separated list of the
 289      * constructor's formal parameter types.  For example:
 290      * <pre>{@code
 291      *    public java.util.Hashtable(int,float)
 292      * }</pre>
 293      *
 294      * <p>The only possible modifiers for constructors are the access
 295      * modifiers {@code public}, {@code protected} or
 296      * {@code private}.  Only one of these may appear, or none if the
 297      * constructor has default (package) access.
 298      *
 299      * @return a string describing this {@code Constructor}
 300      * @jls 8.8.3 Constructor Modifiers
 301      * @jls 8.9.2 Enum Body Declarations
 302      */
 303     public String toString() {
 304         return sharedToString(Modifier.constructorModifiers(),
 305                               false,
 306                               parameterTypes,
 307                               exceptionTypes);
 308     }
 309 
 310     @Override
 311     void specificToStringHeader(StringBuilder sb) {
 312         sb.append(getDeclaringClass().getTypeName());
 313     }
 314 
 315     /**
 316      * Returns a string describing this {@code Constructor},
 317      * including type parameters.  The string is formatted as the
 318      * constructor access modifiers, if any, followed by an
 319      * angle-bracketed comma separated list of the constructor's type
 320      * parameters, if any, followed by the fully-qualified name of the
 321      * declaring class, followed by a parenthesized, comma-separated
 322      * list of the constructor's generic formal parameter types.
 323      *
 324      * If this constructor was declared to take a variable number of
 325      * arguments, instead of denoting the last parameter as
 326      * "<code><i>Type</i>[]</code>", it is denoted as
 327      * "<code><i>Type</i>...</code>".
 328      *
 329      * A space is used to separate access modifiers from one another
 330      * and from the type parameters or return type.  If there are no
 331      * type parameters, the type parameter list is elided; if the type
 332      * parameter list is present, a space separates the list from the
 333      * class name.  If the constructor is declared to throw
 334      * exceptions, the parameter list is followed by a space, followed
 335      * by the word "{@code throws}" followed by a
 336      * comma-separated list of the thrown exception types.
 337      *
 338      * <p>The only possible modifiers for constructors are the access
 339      * modifiers {@code public}, {@code protected} or
 340      * {@code private}.  Only one of these may appear, or none if the
 341      * constructor has default (package) access.
 342      *
 343      * @return a string describing this {@code Constructor},
 344      * include type parameters
 345      *
 346      * @since 1.5
 347      * @jls 8.8.3 Constructor Modifiers
 348      * @jls 8.9.2 Enum Body Declarations
 349      */
 350     @Override
 351     public String toGenericString() {
 352         return sharedToGenericString(Modifier.constructorModifiers(), false);
 353     }
 354 
 355     @Override
 356     void specificToGenericStringHeader(StringBuilder sb) {
 357         specificToStringHeader(sb);
 358     }
 359 
 360     /**
 361      * Uses the constructor represented by this {@code Constructor} object to
 362      * create and initialize a new instance of the constructor's
 363      * declaring class, with the specified initialization parameters.
 364      * Individual parameters are automatically unwrapped to match
 365      * primitive formal parameters, and both primitive and reference
 366      * parameters are subject to method invocation conversions as necessary.
 367      *
 368      * <p>If the number of formal parameters required by the underlying constructor
 369      * is 0, the supplied {@code initargs} array may be of length 0 or null.
 370      *
 371      * <p>If the constructor's declaring class is an inner class in a
 372      * non-static context, the first argument to the constructor needs
 373      * to be the enclosing instance; see section 15.9.3 of
 374      * <cite>The Java&trade; Language Specification</cite>.
 375      *
 376      * <p>If the required access and argument checks succeed and the
 377      * instantiation will proceed, the constructor's declaring class
 378      * is initialized if it has not already been initialized.
 379      *
 380      * <p>If the constructor completes normally, returns the newly
 381      * created and initialized instance.
 382      *
 383      * @param initargs array of objects to be passed as arguments to
 384      * the constructor call; values of primitive types are wrapped in
 385      * a wrapper object of the appropriate type (e.g. a {@code float}
 386      * in a {@link java.lang.Float Float})
 387      *
 388      * @return a new object created by calling the constructor
 389      * this object represents
 390      *
 391      * @exception IllegalAccessException    if this {@code Constructor} object
 392      *              is enforcing Java language access control and the underlying
 393      *              constructor is inaccessible.
 394      * @exception IllegalArgumentException  if the number of actual
 395      *              and formal parameters differ; if an unwrapping
 396      *              conversion for primitive arguments fails; or if,
 397      *              after possible unwrapping, a parameter value
 398      *              cannot be converted to the corresponding formal
 399      *              parameter type by a method invocation conversion; if
 400      *              this constructor pertains to an enum type.
 401      * @exception InstantiationException    if the class that declares the
 402      *              underlying constructor represents an abstract class.
 403      * @exception InvocationTargetException if the underlying constructor
 404      *              throws an exception.
 405      * @exception ExceptionInInitializerError if the initialization provoked
 406      *              by this method fails.
 407      */
 408     @CallerSensitive
 409     public T newInstance(Object ... initargs)
 410         throws InstantiationException, IllegalAccessException,
 411                IllegalArgumentException, InvocationTargetException
 412     {
 413         if (!override) {
 414             if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
 415                 Class<?> caller = Reflection.getCallerClass();
 416                 checkAccess(caller, clazz, null, modifiers);
 417             }
 418         }
 419         if ((clazz.getModifiers() & Modifier.ENUM) != 0)
 420             throw new IllegalArgumentException("Cannot reflectively create enum objects");
 421         ConstructorAccessor ca = constructorAccessor;   // read volatile
 422         if (ca == null) {
 423             ca = acquireConstructorAccessor();
 424         }
 425         @SuppressWarnings("unchecked")
 426         T inst = (T) ca.newInstance(initargs);
 427         return inst;
 428     }
 429 
 430     /**
 431      * {@inheritDoc}
 432      * @since 1.5
 433      */
 434     @Override
 435     public boolean isVarArgs() {
 436         return super.isVarArgs();
 437     }
 438 
 439     /**
 440      * {@inheritDoc}
 441      * @jls 13.1 The Form of a Binary
 442      * @since 1.5
 443      */
 444     @Override
 445     public boolean isSynthetic() {
 446         return super.isSynthetic();
 447     }
 448 
 449     // NOTE that there is no synchronization used here. It is correct
 450     // (though not efficient) to generate more than one
 451     // ConstructorAccessor for a given Constructor. However, avoiding
 452     // synchronization will probably make the implementation more
 453     // scalable.
 454     private ConstructorAccessor acquireConstructorAccessor() {
 455         // First check to see if one has been created yet, and take it
 456         // if so.
 457         ConstructorAccessor tmp = null;
 458         if (root != null) tmp = root.getConstructorAccessor();
 459         if (tmp != null) {
 460             constructorAccessor = tmp;
 461         } else {
 462             // Otherwise fabricate one and propagate it up to the root
 463             tmp = reflectionFactory.newConstructorAccessor(this);
 464             setConstructorAccessor(tmp);
 465         }
 466 
 467         return tmp;
 468     }
 469 
 470     // Returns ConstructorAccessor for this Constructor object, not
 471     // looking up the chain to the root
 472     ConstructorAccessor getConstructorAccessor() {
 473         return constructorAccessor;
 474     }
 475 
 476     // Sets the ConstructorAccessor for this Constructor object and
 477     // (recursively) its root
 478     void setConstructorAccessor(ConstructorAccessor accessor) {
 479         constructorAccessor = accessor;
 480         // Propagate up
 481         if (root != null) {
 482             root.setConstructorAccessor(accessor);
 483         }
 484     }
 485 
 486     int getSlot() {
 487         return slot;
 488     }
 489 
 490     String getSignature() {
 491         return signature;
 492     }
 493 
 494     byte[] getRawAnnotations() {
 495         return annotations;
 496     }
 497 
 498     byte[] getRawParameterAnnotations() {
 499         return parameterAnnotations;
 500     }
 501 
 502 
 503     /**
 504      * {@inheritDoc}
 505      * @throws NullPointerException  {@inheritDoc}
 506      * @since 1.5
 507      */
 508     public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
 509         return super.getAnnotation(annotationClass);
 510     }
 511 
 512     /**
 513      * {@inheritDoc}
 514      * @since 1.5
 515      */
 516     public Annotation[] getDeclaredAnnotations()  {
 517         return super.getDeclaredAnnotations();
 518     }
 519 
 520     /**
 521      * {@inheritDoc}
 522      * @since 1.5
 523      */
 524     @Override
 525     public Annotation[][] getParameterAnnotations() {
 526         return sharedGetParameterAnnotations(parameterTypes, parameterAnnotations);
 527     }
 528 
 529     @Override
 530     void handleParameterNumberMismatch(int resultLength, int numParameters) {
 531         Class<?> declaringClass = getDeclaringClass();
 532         if (declaringClass.isEnum() ||
 533             declaringClass.isAnonymousClass() ||
 534             declaringClass.isLocalClass() )
 535             return ; // Can't do reliable parameter counting
 536         else {
 537             if (!declaringClass.isMemberClass() || // top-level
 538                 // Check for the enclosing instance parameter for
 539                 // non-static member classes
 540                 (declaringClass.isMemberClass() &&
 541                  ((declaringClass.getModifiers() & Modifier.STATIC) == 0)  &&
 542                  resultLength + 1 != numParameters) ) {
 543                 throw new AnnotationFormatError(
 544                           "Parameter annotations don't match number of parameters");
 545             }
 546         }
 547     }
 548 
 549     /**
 550      * {@inheritDoc}
 551      * @since 1.8
 552      */
 553     @Override
 554     public AnnotatedType getAnnotatedReturnType() {
 555         return getAnnotatedReturnType0(getDeclaringClass());
 556     }
 557 
 558     /**
 559      * {@inheritDoc}
 560      * @since 1.8
 561      */
 562     @Override
 563     public AnnotatedType getAnnotatedReceiverType() {
 564         Class<?> thisDeclClass = getDeclaringClass();
 565         Class<?> enclosingClass = thisDeclClass.getEnclosingClass();
 566 
 567         if (enclosingClass == null) {
 568             // A Constructor for a top-level class
 569             return null;
 570         }
 571 
 572         Class<?> outerDeclaringClass = thisDeclClass.getDeclaringClass();
 573         if (outerDeclaringClass == null) {
 574             // A constructor for a local or anonymous class
 575             return null;
 576         }
 577 
 578         // Either static nested or inner class
 579         if (Modifier.isStatic(thisDeclClass.getModifiers())) {
 580             // static nested
 581             return null;
 582         }
 583 
 584         // A Constructor for an inner class
 585         return TypeAnnotationParser.buildAnnotatedType(getTypeAnnotationBytes0(),
 586                 SharedSecrets.getJavaLangAccess().
 587                     getConstantPool(thisDeclClass),
 588                 this,
 589                 thisDeclClass,
 590                 enclosingClass,
 591                 TypeAnnotation.TypeAnnotationTarget.METHOD_RECEIVER);
 592     }
 593 }