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      */
 301     public String toString() {
 302         return sharedToString(Modifier.constructorModifiers(),
 303                               false,
 304                               parameterTypes,
 305                               exceptionTypes);
 306     }
 307 
 308     @Override
 309     void specificToStringHeader(StringBuilder sb) {
 310         sb.append(getDeclaringClass().getTypeName());
 311     }
 312 
 313     /**
 314      * Returns a string describing this {@code Constructor},
 315      * including type parameters.  The string is formatted as the
 316      * constructor access modifiers, if any, followed by an
 317      * angle-bracketed comma separated list of the constructor's type
 318      * parameters, if any, followed by the fully-qualified name of the
 319      * declaring class, followed by a parenthesized, comma-separated
 320      * list of the constructor's generic formal parameter types.
 321      *
 322      * If this constructor was declared to take a variable number of
 323      * arguments, instead of denoting the last parameter as
 324      * "<tt><i>Type</i>[]</tt>", it is denoted as
 325      * "<tt><i>Type</i>...</tt>".
 326      *
 327      * A space is used to separate access modifiers from one another
 328      * and from the type parameters or return type.  If there are no
 329      * type parameters, the type parameter list is elided; if the type
 330      * parameter list is present, a space separates the list from the
 331      * class name.  If the constructor is declared to throw
 332      * exceptions, the parameter list is followed by a space, followed
 333      * by the word "{@code throws}" followed by a
 334      * comma-separated list of the thrown exception types.
 335      *
 336      * <p>The only possible modifiers for constructors are the access
 337      * modifiers {@code public}, {@code protected} or
 338      * {@code private}.  Only one of these may appear, or none if the
 339      * constructor has default (package) access.
 340      *
 341      * @return a string describing this {@code Constructor},
 342      * include type parameters
 343      *
 344      * @since 1.5
 345      * @jls 8.8.3. Constructor Modifiers
 346      */
 347     @Override
 348     public String toGenericString() {
 349         return sharedToGenericString(Modifier.constructorModifiers(), false);
 350     }
 351 
 352     @Override
 353     void specificToGenericStringHeader(StringBuilder sb) {
 354         specificToStringHeader(sb);
 355     }
 356 
 357     /**
 358      * Uses the constructor represented by this {@code Constructor} object to
 359      * create and initialize a new instance of the constructor's
 360      * declaring class, with the specified initialization parameters.
 361      * Individual parameters are automatically unwrapped to match
 362      * primitive formal parameters, and both primitive and reference
 363      * parameters are subject to method invocation conversions as necessary.
 364      *
 365      * <p>If the number of formal parameters required by the underlying constructor
 366      * is 0, the supplied {@code initargs} array may be of length 0 or null.
 367      *
 368      * <p>If the constructor's declaring class is an inner class in a
 369      * non-static context, the first argument to the constructor needs
 370      * to be the enclosing instance; see section 15.9.3 of
 371      * <cite>The Java&trade; Language Specification</cite>.
 372      *
 373      * <p>If the required access and argument checks succeed and the
 374      * instantiation will proceed, the constructor's declaring class
 375      * is initialized if it has not already been initialized.
 376      *
 377      * <p>If the constructor completes normally, returns the newly
 378      * created and initialized instance.
 379      *
 380      * @param initargs array of objects to be passed as arguments to
 381      * the constructor call; values of primitive types are wrapped in
 382      * a wrapper object of the appropriate type (e.g. a {@code float}
 383      * in a {@link java.lang.Float Float})
 384      *
 385      * @return a new object created by calling the constructor
 386      * this object represents
 387      *
 388      * @exception IllegalAccessException    if this {@code Constructor} object
 389      *              is enforcing Java language access control and the underlying
 390      *              constructor is inaccessible.
 391      * @exception IllegalArgumentException  if the number of actual
 392      *              and formal parameters differ; if an unwrapping
 393      *              conversion for primitive arguments fails; or if,
 394      *              after possible unwrapping, a parameter value
 395      *              cannot be converted to the corresponding formal
 396      *              parameter type by a method invocation conversion; if
 397      *              this constructor pertains to an enum type.
 398      * @exception InstantiationException    if the class that declares the
 399      *              underlying constructor represents an abstract class.
 400      * @exception InvocationTargetException if the underlying constructor
 401      *              throws an exception.
 402      * @exception ExceptionInInitializerError if the initialization provoked
 403      *              by this method fails.
 404      */
 405     @CallerSensitive
 406     public T newInstance(Object ... initargs)
 407         throws InstantiationException, IllegalAccessException,
 408                IllegalArgumentException, InvocationTargetException
 409     {
 410         if (!override) {
 411             if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
 412                 Class<?> caller = Reflection.getCallerClass();
 413                 checkAccess(caller, clazz, null, modifiers);
 414             }
 415         }
 416         if ((clazz.getModifiers() & Modifier.ENUM) != 0)
 417             throw new IllegalArgumentException("Cannot reflectively create enum objects");
 418         ConstructorAccessor ca = constructorAccessor;   // read volatile
 419         if (ca == null) {
 420             ca = acquireConstructorAccessor();
 421         }
 422         @SuppressWarnings("unchecked")
 423         T inst = (T) ca.newInstance(initargs);
 424         return inst;
 425     }
 426 
 427     /**
 428      * {@inheritDoc}
 429      * @since 1.5
 430      */
 431     @Override
 432     public boolean isVarArgs() {
 433         return super.isVarArgs();
 434     }
 435 
 436     /**
 437      * {@inheritDoc}
 438      * @jls 13.1 The Form of a Binary
 439      * @since 1.5
 440      */
 441     @Override
 442     public boolean isSynthetic() {
 443         return super.isSynthetic();
 444     }
 445 
 446     // NOTE that there is no synchronization used here. It is correct
 447     // (though not efficient) to generate more than one
 448     // ConstructorAccessor for a given Constructor. However, avoiding
 449     // synchronization will probably make the implementation more
 450     // scalable.
 451     private ConstructorAccessor acquireConstructorAccessor() {
 452         // First check to see if one has been created yet, and take it
 453         // if so.
 454         ConstructorAccessor tmp = null;
 455         if (root != null) tmp = root.getConstructorAccessor();
 456         if (tmp != null) {
 457             constructorAccessor = tmp;
 458         } else {
 459             // Otherwise fabricate one and propagate it up to the root
 460             tmp = reflectionFactory.newConstructorAccessor(this);
 461             setConstructorAccessor(tmp);
 462         }
 463 
 464         return tmp;
 465     }
 466 
 467     // Returns ConstructorAccessor for this Constructor object, not
 468     // looking up the chain to the root
 469     ConstructorAccessor getConstructorAccessor() {
 470         return constructorAccessor;
 471     }
 472 
 473     // Sets the ConstructorAccessor for this Constructor object and
 474     // (recursively) its root
 475     void setConstructorAccessor(ConstructorAccessor accessor) {
 476         constructorAccessor = accessor;
 477         // Propagate up
 478         if (root != null) {
 479             root.setConstructorAccessor(accessor);
 480         }
 481     }
 482 
 483     int getSlot() {
 484         return slot;
 485     }
 486 
 487     String getSignature() {
 488         return signature;
 489     }
 490 
 491     byte[] getRawAnnotations() {
 492         return annotations;
 493     }
 494 
 495     byte[] getRawParameterAnnotations() {
 496         return parameterAnnotations;
 497     }
 498 
 499 
 500     /**
 501      * {@inheritDoc}
 502      * @throws NullPointerException  {@inheritDoc}
 503      * @since 1.5
 504      */
 505     public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
 506         return super.getAnnotation(annotationClass);
 507     }
 508 
 509     /**
 510      * {@inheritDoc}
 511      * @since 1.5
 512      */
 513     public Annotation[] getDeclaredAnnotations()  {
 514         return super.getDeclaredAnnotations();
 515     }
 516 
 517     /**
 518      * {@inheritDoc}
 519      * @since 1.5
 520      */
 521     @Override
 522     public Annotation[][] getParameterAnnotations() {
 523         return sharedGetParameterAnnotations(parameterTypes, parameterAnnotations);
 524     }
 525 
 526     @Override
 527     void handleParameterNumberMismatch(int resultLength, int numParameters) {
 528         Class<?> declaringClass = getDeclaringClass();
 529         if (declaringClass.isEnum() ||
 530             declaringClass.isAnonymousClass() ||
 531             declaringClass.isLocalClass() )
 532             return ; // Can't do reliable parameter counting
 533         else {
 534             if (!declaringClass.isMemberClass() || // top-level
 535                 // Check for the enclosing instance parameter for
 536                 // non-static member classes
 537                 (declaringClass.isMemberClass() &&
 538                  ((declaringClass.getModifiers() & Modifier.STATIC) == 0)  &&
 539                  resultLength + 1 != numParameters) ) {
 540                 throw new AnnotationFormatError(
 541                           "Parameter annotations don't match number of parameters");
 542             }
 543         }
 544     }
 545 
 546     /**
 547      * {@inheritDoc}
 548      * @since 1.8
 549      */
 550     @Override
 551     public AnnotatedType getAnnotatedReturnType() {
 552         return getAnnotatedReturnType0(getDeclaringClass());
 553     }
 554 
 555     /**
 556      * {@inheritDoc}
 557      * @since 1.8
 558      */
 559     @Override
 560     public AnnotatedType getAnnotatedReceiverType() {
 561         Class<?> thisDeclClass = getDeclaringClass();
 562         Class<?> enclosingClass = thisDeclClass.getEnclosingClass();
 563 
 564         if (enclosingClass == null) {
 565             // A Constructor for a top-level class
 566             return null;
 567         }
 568 
 569         Class<?> outerDeclaringClass = thisDeclClass.getDeclaringClass();
 570         if (outerDeclaringClass == null) {
 571             // A constructor for a local or anonymous class
 572             return null;
 573         }
 574 
 575         // Either static nested or inner class
 576         if (Modifier.isStatic(thisDeclClass.getModifiers())) {
 577             // static nested
 578             return null;
 579         }
 580 
 581         // A Constructor for an inner class
 582         return TypeAnnotationParser.buildAnnotatedType(getTypeAnnotationBytes0(),
 583                 sun.misc.SharedSecrets.getJavaLangAccess().
 584                     getConstantPool(thisDeclClass),
 585                 this,
 586                 thisDeclClass,
 587                 enclosingClass,
 588                 TypeAnnotation.TypeAnnotationTarget.METHOD_RECEIVER);
 589     }
 590 }