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