Home | History | Annotate | Download | only in reflect
      1 /*
      2  * Copyright (C) 2014 The Android Open Source Project
      3  * Copyright (c) 1996, 2010, Oracle and/or its affiliates. All rights reserved.
      4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
      5  *
      6  * This code is free software; you can redistribute it and/or modify it
      7  * under the terms of the GNU General Public License version 2 only, as
      8  * published by the Free Software Foundation.  Oracle designates this
      9  * particular file as subject to the "Classpath" exception as provided
     10  * by Oracle in the LICENSE file that accompanied this code.
     11  *
     12  * This code is distributed in the hope that it will be useful, but WITHOUT
     13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
     14  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
     15  * version 2 for more details (a copy is included in the LICENSE file that
     16  * accompanied this code).
     17  *
     18  * You should have received a copy of the GNU General Public License version
     19  * 2 along with this work; if not, write to the Free Software Foundation,
     20  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
     21  *
     22  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
     23  * or visit www.oracle.com if you need additional information or have any
     24  * questions.
     25  */
     26 
     27 package java.lang.reflect;
     28 
     29 import sun.reflect.CallerSensitive;
     30 import java.util.Comparator;
     31 import java.util.List;
     32 import libcore.reflect.Types;
     33 
     34 import java.lang.annotation.Annotation;
     35 
     36 /**
     37  * {@code Constructor} provides information about, and access to, a single
     38  * constructor for a class.
     39  *
     40  * <p>{@code Constructor} permits widening conversions to occur when matching the
     41  * actual parameters to newInstance() with the underlying
     42  * constructor's formal parameters, but throws an
     43  * {@code IllegalArgumentException} if a narrowing conversion would occur.
     44  *
     45  * @param <T> the class in which the constructor is declared
     46  *
     47  * @see Member
     48  * @see java.lang.Class
     49  * @see java.lang.Class#getConstructors()
     50  * @see java.lang.Class#getConstructor(Class[])
     51  * @see java.lang.Class#getDeclaredConstructors()
     52  *
     53  * @author      Kenneth Russell
     54  * @author      Nakul Saraiya
     55  */
     56 public final class Constructor<T> extends AbstractMethod implements
     57                                                     GenericDeclaration,
     58                                                     Member {
     59     private static final Comparator<Method> ORDER_BY_SIGNATURE = null; // Unused; must match Method.
     60 
     61     private final Class<?> serializationClass;
     62     private final Class<?> serializationCtor;
     63 
     64     private Constructor() {
     65       this(null, null);
     66     }
     67 
     68     private Constructor(Class<?> serializationCtor,
     69         Class<?> serializationClass) {
     70         this.serializationCtor = serializationCtor;
     71         this.serializationClass = serializationClass;
     72     }
     73 
     74     /**
     75      * @hide
     76      */
     77     public Constructor<T> serializationCopy(Class<?> ctor, Class<?> cl) {
     78         return new Constructor<T>(ctor, cl);
     79     }
     80 
     81     /**
     82      * Returns the {@code Class} object representing the class that declares
     83      * the constructor represented by this {@code Constructor} object.
     84      */
     85     public Class<T> getDeclaringClass() {
     86         return (Class<T>) super.getDeclaringClass();
     87     }
     88 
     89     /**
     90      * Returns the name of this constructor, as a string.  This is
     91      * the binary name of the constructor's declaring class.
     92      */
     93     public String getName() {
     94         return getDeclaringClass().getName();
     95     }
     96 
     97     /**
     98      * Returns the Java language modifiers for the constructor
     99      * represented by this {@code Constructor} object, as an integer. The
    100      * {@code Modifier} class should be used to decode the modifiers.
    101      *
    102      * @see Modifier
    103      */
    104     public int getModifiers() {
    105         return super.getModifiers();
    106     }
    107 
    108     /**
    109      * Returns an array of {@code TypeVariable} objects that represent the
    110      * type variables declared by the generic declaration represented by this
    111      * {@code GenericDeclaration} object, in declaration order.  Returns an
    112      * array of length 0 if the underlying generic declaration declares no type
    113      * variables.
    114      *
    115      * @return an array of {@code TypeVariable} objects that represent
    116      *     the type variables declared by this generic declaration
    117      * @throws GenericSignatureFormatError if the generic
    118      *     signature of this generic declaration does not conform to
    119      *     the format specified in
    120      *     <cite>The Java&trade; Virtual Machine Specification</cite>
    121      * @since 1.5
    122      */
    123     public TypeVariable<Constructor<T>>[] getTypeParameters() {
    124       GenericInfo info = getMethodOrConstructorGenericInfo();
    125       return (TypeVariable<Constructor<T>>[]) info.formalTypeParameters.clone();
    126     }
    127 
    128 
    129     /**
    130      * Returns an array of {@code Class} objects that represent the formal
    131      * parameter types, in declaration order, of the constructor
    132      * represented by this {@code Constructor} object.  Returns an array of
    133      * length 0 if the underlying constructor takes no parameters.
    134      *
    135      * @return the parameter types for the constructor this object
    136      * represents
    137      */
    138     public Class<?>[] getParameterTypes() {
    139         return super.getParameterTypes();
    140     }
    141 
    142 
    143     /**
    144      * Returns an array of {@code Type} objects that represent the formal
    145      * parameter types, in declaration order, of the method represented by
    146      * this {@code Constructor} object. Returns an array of length 0 if the
    147      * underlying method takes no parameters.
    148      *
    149      * <p>If a formal parameter type is a parameterized type,
    150      * the {@code Type} object returned for it must accurately reflect
    151      * the actual type parameters used in the source code.
    152      *
    153      * <p>If a formal parameter type is a type variable or a parameterized
    154      * type, it is created. Otherwise, it is resolved.
    155      *
    156      * @return an array of {@code Type}s that represent the formal
    157      *     parameter types of the underlying method, in declaration order
    158      * @throws GenericSignatureFormatError
    159      *     if the generic method signature does not conform to the format
    160      *     specified in
    161      *     <cite>The Java&trade; Virtual Machine Specification</cite>
    162      * @throws TypeNotPresentException if any of the parameter
    163      *     types of the underlying method refers to a non-existent type
    164      *     declaration
    165      * @throws MalformedParameterizedTypeException if any of
    166      *     the underlying method's parameter types refer to a parameterized
    167      *     type that cannot be instantiated for any reason
    168      * @since 1.5
    169      */
    170     public Type[] getGenericParameterTypes() {
    171         return super.getGenericParameterTypes();
    172     }
    173 
    174 
    175     /**
    176      * Returns an array of {@code Class} objects that represent the types
    177      * of exceptions declared to be thrown by the underlying constructor
    178      * represented by this {@code Constructor} object.  Returns an array of
    179      * length 0 if the constructor declares no exceptions in its {@code throws} clause.
    180      *
    181      * @return the exception types declared as being thrown by the
    182      * constructor this object represents
    183      */
    184     public native Class<?>[] getExceptionTypes();
    185 
    186     /**
    187      * Returns an array of {@code Type} objects that represent the
    188      * exceptions declared to be thrown by this {@code Constructor} object.
    189      * Returns an array of length 0 if the underlying method declares
    190      * no exceptions in its {@code throws} clause.
    191      *
    192      * <p>If an exception type is a type variable or a parameterized
    193      * type, it is created. Otherwise, it is resolved.
    194      *
    195      * @return an array of Types that represent the exception types
    196      *     thrown by the underlying method
    197      * @throws GenericSignatureFormatError
    198      *     if the generic method signature does not conform to the format
    199      *     specified in
    200      *     <cite>The Java&trade; Virtual Machine Specification</cite>
    201      * @throws TypeNotPresentException if the underlying method's
    202      *     {@code throws} clause refers to a non-existent type declaration
    203      * @throws MalformedParameterizedTypeException if
    204      *     the underlying method's {@code throws} clause refers to a
    205      *     parameterized type that cannot be instantiated for any reason
    206      * @since 1.5
    207      */
    208       public Type[] getGenericExceptionTypes() {
    209           return super.getGenericExceptionTypes();
    210       }
    211 
    212     /**
    213      * Compares this {@code Constructor} against the specified object.
    214      * Returns true if the objects are the same.  Two {@code Constructor} objects are
    215      * the same if they were declared by the same class and have the
    216      * same formal parameter types.
    217      */
    218     public boolean equals(Object obj) {
    219         if (obj != null && obj instanceof Constructor) {
    220             Constructor<?> other = (Constructor<?>)obj;
    221             if (getDeclaringClass() == other.getDeclaringClass()) {
    222                 /* Avoid unnecessary cloning */
    223                 // Android changed: Use getParameterTypes.
    224                 Class<?>[] params1 = getParameterTypes();
    225                 Class<?>[] params2 = other.getParameterTypes();
    226                 if (params1.length == params2.length) {
    227                     for (int i = 0; i < params1.length; i++) {
    228                         if (params1[i] != params2[i])
    229                             return false;
    230                     }
    231                     return true;
    232                 }
    233             }
    234         }
    235         return false;
    236     }
    237 
    238     /**
    239      * Returns a hashcode for this {@code Constructor}. The hashcode is
    240      * the same as the hashcode for the underlying constructor's
    241      * declaring class name.
    242      */
    243     public int hashCode() {
    244         return getDeclaringClass().getName().hashCode();
    245     }
    246 
    247     /**
    248      * Returns a string describing this {@code Constructor}.  The string is
    249      * formatted as the constructor access modifiers, if any,
    250      * followed by the fully-qualified name of the declaring class,
    251      * followed by a parenthesized, comma-separated list of the
    252      * constructor's formal parameter types.  For example:
    253      * <pre>
    254      *    public java.util.Hashtable(int,float)
    255      * </pre>
    256      *
    257      * <p>The only possible modifiers for constructors are the access
    258      * modifiers {@code public}, {@code protected} or
    259      * {@code private}.  Only one of these may appear, or none if the
    260      * constructor has default (package) access.
    261      */
    262     public String toString() {
    263         try {
    264             StringBuffer sb = new StringBuffer();
    265             int mod = getModifiers() & Modifier.constructorModifiers();
    266             if (mod != 0) {
    267                 sb.append(Modifier.toString(mod) + " ");
    268             }
    269             sb.append(Field.getTypeName(getDeclaringClass()));
    270             sb.append("(");
    271             Class<?>[] params = getParameterTypes();
    272             for (int j = 0; j < params.length; j++) {
    273                 sb.append(Field.getTypeName(params[j]));
    274                 if (j < (params.length - 1))
    275                     sb.append(",");
    276             }
    277             sb.append(")");
    278             Class<?>[] exceptions = getExceptionTypes();
    279             if (exceptions.length > 0) {
    280                 sb.append(" throws ");
    281                 for (int k = 0; k < exceptions.length; k++) {
    282                     sb.append(exceptions[k].getName());
    283                     if (k < (exceptions.length - 1))
    284                         sb.append(",");
    285                 }
    286             }
    287             return sb.toString();
    288         } catch (Exception e) {
    289             return "<" + e + ">";
    290         }
    291     }
    292 
    293     /**
    294      * Returns a string describing this {@code Constructor},
    295      * including type parameters.  The string is formatted as the
    296      * constructor access modifiers, if any, followed by an
    297      * angle-bracketed comma separated list of the constructor's type
    298      * parameters, if any, followed by the fully-qualified name of the
    299      * declaring class, followed by a parenthesized, comma-separated
    300      * list of the constructor's generic formal parameter types.
    301      *
    302      * If this constructor was declared to take a variable number of
    303      * arguments, instead of denoting the last parameter as
    304      * "<tt><i>Type</i>[]</tt>", it is denoted as
    305      * "<tt><i>Type</i>...</tt>".
    306      *
    307      * A space is used to separate access modifiers from one another
    308      * and from the type parameters or return type.  If there are no
    309      * type parameters, the type parameter list is elided; if the type
    310      * parameter list is present, a space separates the list from the
    311      * class name.  If the constructor is declared to throw
    312      * exceptions, the parameter list is followed by a space, followed
    313      * by the word "{@code throws}" followed by a
    314      * comma-separated list of the thrown exception types.
    315      *
    316      * <p>The only possible modifiers for constructors are the access
    317      * modifiers {@code public}, {@code protected} or
    318      * {@code private}.  Only one of these may appear, or none if the
    319      * constructor has default (package) access.
    320      *
    321      * @return a string describing this {@code Constructor},
    322      * include type parameters
    323      *
    324      * @since 1.5
    325      */
    326     public String toGenericString() {
    327         try {
    328             StringBuilder sb = new StringBuilder();
    329             int mod = getModifiers() & Modifier.constructorModifiers();
    330             if (mod != 0) {
    331                 sb.append(Modifier.toString(mod) + " ");
    332             }
    333             TypeVariable<?>[] typeparms = getTypeParameters();
    334             if (typeparms.length > 0) {
    335                 boolean first = true;
    336                 sb.append("<");
    337                 for(TypeVariable<?> typeparm: typeparms) {
    338                     if (!first)
    339                         sb.append(",");
    340                     // Class objects can't occur here; no need to test
    341                     // and call Class.getName().
    342                     sb.append(typeparm.toString());
    343                     first = false;
    344                 }
    345                 sb.append("> ");
    346             }
    347             sb.append(Field.getTypeName(getDeclaringClass()));
    348             sb.append("(");
    349             Type[] params = getGenericParameterTypes();
    350             for (int j = 0; j < params.length; j++) {
    351                 String param = (params[j] instanceof Class<?>)?
    352                     Field.getTypeName((Class<?>)params[j]):
    353                     (params[j].toString());
    354                 if (isVarArgs() && (j == params.length - 1)) // replace T[] with T...
    355                     param = param.replaceFirst("\\[\\]$", "...");
    356                 sb.append(param);
    357                 if (j < (params.length - 1))
    358                     sb.append(",");
    359             }
    360             sb.append(")");
    361             Type[] exceptions = getGenericExceptionTypes();
    362             if (exceptions.length > 0) {
    363                 sb.append(" throws ");
    364                 for (int k = 0; k < exceptions.length; k++) {
    365                     sb.append((exceptions[k] instanceof Class)?
    366                               ((Class<?>)exceptions[k]).getName():
    367                               exceptions[k].toString());
    368                     if (k < (exceptions.length - 1))
    369                         sb.append(",");
    370                 }
    371             }
    372             return sb.toString();
    373         } catch (Exception e) {
    374             return "<" + e + ">";
    375         }
    376     }
    377 
    378     /**
    379      * Uses the constructor represented by this {@code Constructor} object to
    380      * create and initialize a new instance of the constructor's
    381      * declaring class, with the specified initialization parameters.
    382      * Individual parameters are automatically unwrapped to match
    383      * primitive formal parameters, and both primitive and reference
    384      * parameters are subject to method invocation conversions as necessary.
    385      *
    386      * <p>If the number of formal parameters required by the underlying constructor
    387      * is 0, the supplied {@code initargs} array may be of length 0 or null.
    388      *
    389      * <p>If the constructor's declaring class is an inner class in a
    390      * non-static context, the first argument to the constructor needs
    391      * to be the enclosing instance; see section 15.9.3 of
    392      * <cite>The Java&trade; Language Specification</cite>.
    393      *
    394      * <p>If the required access and argument checks succeed and the
    395      * instantiation will proceed, the constructor's declaring class
    396      * is initialized if it has not already been initialized.
    397      *
    398      * <p>If the constructor completes normally, returns the newly
    399      * created and initialized instance.
    400      *
    401      * @param args array of objects to be passed as arguments to
    402      * the constructor call; values of primitive types are wrapped in
    403      * a wrapper object of the appropriate type (e.g. a {@code float}
    404      * in a {@link java.lang.Float Float})
    405      *
    406      * @return a new object created by calling the constructor
    407      * this object represents
    408      *
    409      * @exception IllegalAccessException    if this {@code Constructor} object
    410      *              is enforcing Java language access control and the underlying
    411      *              constructor is inaccessible.
    412      * @exception IllegalArgumentException  if the number of actual
    413      *              and formal parameters differ; if an unwrapping
    414      *              conversion for primitive arguments fails; or if,
    415      *              after possible unwrapping, a parameter value
    416      *              cannot be converted to the corresponding formal
    417      *              parameter type by a method invocation conversion; if
    418      *              this constructor pertains to an enum type.
    419      * @exception InstantiationException    if the class that declares the
    420      *              underlying constructor represents an abstract class.
    421      * @exception InvocationTargetException if the underlying constructor
    422      *              throws an exception.
    423      * @exception ExceptionInInitializerError if the initialization provoked
    424      *              by this method fails.
    425      */
    426     // Android changed param name s/initargs/args
    427     public T newInstance(Object... args) throws InstantiationException,
    428             IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    429         if (serializationClass == null) {
    430             return newInstance0(args);
    431         } else {
    432             return (T) newInstanceFromSerialization(serializationCtor, serializationClass);
    433         }
    434     }
    435 
    436     private static native Object newInstanceFromSerialization(Class<?> ctorClass, Class<?> allocClass)
    437         throws InstantiationException, IllegalArgumentException, InvocationTargetException;
    438 
    439     private native T newInstance0(Object... args) throws InstantiationException,
    440             IllegalAccessException, IllegalArgumentException, InvocationTargetException;
    441 
    442     /**
    443      * Returns {@code true} if this constructor was declared to take
    444      * a variable number of arguments; returns {@code false}
    445      * otherwise.
    446      *
    447      * @return {@code true} if an only if this constructor was declared to
    448      * take a variable number of arguments.
    449      * @since 1.5
    450      */
    451     public boolean isVarArgs() {
    452         return (getModifiers() & Modifier.VARARGS) != 0;
    453     }
    454 
    455     /**
    456      * Returns {@code true} if this constructor is a synthetic
    457      * constructor; returns {@code false} otherwise.
    458      *
    459      * @return true if and only if this constructor is a synthetic
    460      * constructor as defined by
    461      * <cite>The Java&trade; Language Specification</cite>.
    462      * @since 1.5
    463      */
    464     public boolean isSynthetic() {
    465         return Modifier.isSynthetic(getModifiers());
    466     }
    467 
    468     String getSignature() {
    469         StringBuilder result = new StringBuilder();
    470 
    471         result.append('(');
    472         Class<?>[] parameterTypes = getParameterTypes();
    473         for (Class<?> parameterType : parameterTypes) {
    474             result.append(Types.getSignature(parameterType));
    475         }
    476         result.append(")V");
    477 
    478         return result.toString();
    479     }
    480 
    481     /**
    482      * @throws NullPointerException {@inheritDoc}
    483      * @since 1.5
    484      */
    485     @Override public <A extends Annotation> A getAnnotation(Class<A> annotationType) {
    486         if (annotationType == null) {
    487             throw new NullPointerException("annotationType == null");
    488         }
    489         return getAnnotationNative(annotationType);
    490     }
    491     private native <A extends Annotation> A getAnnotationNative(Class<A> annotationType);
    492 
    493     /**
    494      * @since 1.5
    495      */
    496     @Override public native Annotation[] getDeclaredAnnotations();
    497 
    498     @Override public boolean isAnnotationPresent(Class<? extends Annotation> annotationType) {
    499         if (annotationType == null) {
    500             throw new NullPointerException("annotationType == null");
    501         }
    502         return isAnnotationPresentNative(annotationType);
    503     }
    504     private native boolean isAnnotationPresentNative(Class<? extends Annotation> annotationType);
    505 
    506     /**
    507      * Returns an array of arrays that represent the annotations on the formal
    508      * parameters, in declaration order, of the method represented by
    509      * this {@code Constructor} object. (Returns an array of length zero if the
    510      * underlying method is parameterless.  If the method has one or more
    511      * parameters, a nested array of length zero is returned for each parameter
    512      * with no annotations.) The annotation objects contained in the returned
    513      * arrays are serializable.  The caller of this method is free to modify
    514      * the returned arrays; it will have no effect on the arrays returned to
    515      * other callers.
    516      *
    517      * @return an array of arrays that represent the annotations on the formal
    518      *    parameters, in declaration order, of the method represented by this
    519      *    Constructor object
    520      * @since 1.5
    521      */
    522     public Annotation[][] getParameterAnnotations() {
    523         Annotation[][] parameterAnnotations = getParameterAnnotationsNative();
    524         if (parameterAnnotations == null) {
    525           parameterAnnotations = new Annotation[getParameterTypes().length][0];
    526         }
    527         return parameterAnnotations;
    528     }
    529     private native Annotation[][] getParameterAnnotationsNative();
    530 }
    531