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