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