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