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