1 /*
2  * Copyright (C) 2014 The Android Open Source Project
3  * Copyright (c) 1996, 2013, 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 dalvik.annotation.optimization.FastNative;
30 import libcore.util.EmptyArray;
31 
32 import java.lang.annotation.Annotation;
33 import java.util.Comparator;
34 
35 /**
36  * {@code Constructor} provides information about, and access to, a single
37  * constructor for a class.
38  *
39  * <p>{@code Constructor} permits widening conversions to occur when matching the
40  * actual parameters to newInstance() with the underlying
41  * constructor's formal parameters, but throws an
42  * {@code IllegalArgumentException} if a narrowing conversion would occur.
43  *
44  * @param <T> the class in which the constructor is declared
45  *
46  * @see Member
47  * @see java.lang.Class
48  * @see java.lang.Class#getConstructors()
49  * @see java.lang.Class#getConstructor(Class[])
50  * @see java.lang.Class#getDeclaredConstructors()
51  *
52  * @author      Kenneth Russell
53  * @author      Nakul Saraiya
54  */
55 public final class Constructor<T> extends Executable {
56     private static final Comparator<Method> ORDER_BY_SIGNATURE = null; // Unused; must match Method.
57 
58     private final Class<?> serializationClass;
59     private final Class<?> serializationCtor;
60 
Constructor()61     private Constructor() {
62       this(null, null);
63     }
64 
Constructor(Class<?> serializationCtor, Class<?> serializationClass)65     private Constructor(Class<?> serializationCtor,
66         Class<?> serializationClass) {
67         this.serializationCtor = serializationCtor;
68         this.serializationClass = serializationClass;
69     }
70 
71     /**
72      * @hide
73      */
serializationCopy(Class<?> ctor, Class<?> cl)74     public Constructor<T> serializationCopy(Class<?> ctor, Class<?> cl) {
75         return new Constructor<T>(ctor, cl);
76     }
77 
78     @Override
hasGenericInformation()79     boolean hasGenericInformation() {
80         // Android-changed: Signature retrieval is handled in Executable.
81         return super.hasGenericInformationInternal();
82     }
83 
84     /**
85      * {@inheritDoc}
86      */
87     @Override
88     @SuppressWarnings({"rawtypes", "unchecked"})
getDeclaringClass()89     public Class<T> getDeclaringClass() {
90         // Android-changed: This is handled by Executable.
91         return (Class<T>) super.getDeclaringClassInternal();
92     }
93 
94     /**
95      * Returns the name of this constructor, as a string.  This is
96      * the binary name of the constructor's declaring class.
97      */
98     @Override
getName()99     public String getName() {
100         return getDeclaringClass().getName();
101     }
102 
103     /**
104      * {@inheritDoc}
105      */
106     @Override
getModifiers()107     public int getModifiers() {
108         // Android-changed: This is handled by Executable.
109         return super.getModifiersInternal();
110     }
111 
112     /**
113      * {@inheritDoc}
114      * @throws GenericSignatureFormatError {@inheritDoc}
115      * @since 1.5
116      */
117     @Override
118     @SuppressWarnings({"rawtypes", "unchecked"})
getTypeParameters()119     public TypeVariable<Constructor<T>>[] getTypeParameters() {
120         // Android-changed: This is mostly handled by Executable.
121         GenericInfo info = getMethodOrConstructorGenericInfoInternal();
122         return (TypeVariable<Constructor<T>>[]) info.formalTypeParameters.clone();
123     }
124 
125 
126     /**
127      * {@inheritDoc}
128      */
129     @Override
getParameterTypes()130     public Class<?>[] getParameterTypes() {
131         // Android-changed: This is handled by Executable.
132         Class<?>[] paramTypes = super.getParameterTypesInternal();
133         if (paramTypes == null) {
134             return EmptyArray.CLASS;
135         }
136 
137         return paramTypes;
138     }
139 
140     /**
141      * {@inheritDoc}
142      * @since 1.8
143      */
getParameterCount()144     public int getParameterCount() {
145         // Android-changed: This is handled by Executable.
146         return super.getParameterCountInternal();
147     }
148 
149     /**
150      * {@inheritDoc}
151      * @throws GenericSignatureFormatError {@inheritDoc}
152      * @throws TypeNotPresentException {@inheritDoc}
153      * @throws MalformedParameterizedTypeException {@inheritDoc}
154      * @since 1.5
155      */
156     @Override
getGenericParameterTypes()157     public Type[] getGenericParameterTypes() {
158         return super.getGenericParameterTypes();
159     }
160 
161     /**
162      * {@inheritDoc}
163      */
164     @Override
165     @FastNative
getExceptionTypes()166     public native Class<?>[] getExceptionTypes();
167 
168     /**
169      * {@inheritDoc}
170      * @throws GenericSignatureFormatError {@inheritDoc}
171      * @throws TypeNotPresentException {@inheritDoc}
172      * @throws MalformedParameterizedTypeException {@inheritDoc}
173      * @since 1.5
174      */
175     @Override
getGenericExceptionTypes()176     public Type[] getGenericExceptionTypes() {
177         return super.getGenericExceptionTypes();
178     }
179 
180     /**
181      * Compares this {@code Constructor} against the specified object.
182      * Returns true if the objects are the same.  Two {@code Constructor} objects are
183      * the same if they were declared by the same class and have the
184      * same formal parameter types.
185      */
equals(Object obj)186     public boolean equals(Object obj) {
187         if (obj != null && obj instanceof Constructor) {
188             Constructor<?> other = (Constructor<?>)obj;
189             if (getDeclaringClass() == other.getDeclaringClass()) {
190                 // Android-changed: Use getParameterTypes.
191                 return equalParamTypes(getParameterTypes(), other.getParameterTypes());
192             }
193         }
194         return false;
195     }
196 
197     /**
198      * Returns a hashcode for this {@code Constructor}. The hashcode is
199      * the same as the hashcode for the underlying constructor's
200      * declaring class name.
201      */
hashCode()202     public int hashCode() {
203         return getDeclaringClass().getName().hashCode();
204     }
205 
206     /**
207      * Returns a string describing this {@code Constructor}.  The string is
208      * formatted as the constructor access modifiers, if any,
209      * followed by the fully-qualified name of the declaring class,
210      * followed by a parenthesized, comma-separated list of the
211      * constructor's formal parameter types.  For example:
212      * <pre>
213      *    public java.util.Hashtable(int,float)
214      * </pre>
215      *
216      * <p>The only possible modifiers for constructors are the access
217      * modifiers {@code public}, {@code protected} or
218      * {@code private}.  Only one of these may appear, or none if the
219      * constructor has default (package) access.
220      *
221      * @return a string describing this {@code Constructor}
222      * @jls 8.8.3. Constructor Modifiers
223      */
toString()224     public String toString() {
225         // Android-changed: Use getParameterTypes().
226         return sharedToString(Modifier.constructorModifiers(),
227                               false,
228                               getParameterTypes(),
229                               getExceptionTypes());
230     }
231 
232     @Override
specificToStringHeader(StringBuilder sb)233     void specificToStringHeader(StringBuilder sb) {
234         sb.append(getDeclaringClass().getTypeName());
235     }
236 
237     /**
238      * Returns a string describing this {@code Constructor},
239      * including type parameters.  The string is formatted as the
240      * constructor access modifiers, if any, followed by an
241      * angle-bracketed comma separated list of the constructor's type
242      * parameters, if any, followed by the fully-qualified name of the
243      * declaring class, followed by a parenthesized, comma-separated
244      * list of the constructor's generic formal parameter types.
245      *
246      * If this constructor was declared to take a variable number of
247      * arguments, instead of denoting the last parameter as
248      * "<tt><i>Type</i>[]</tt>", it is denoted as
249      * "<tt><i>Type</i>...</tt>".
250      *
251      * A space is used to separate access modifiers from one another
252      * and from the type parameters or return type.  If there are no
253      * type parameters, the type parameter list is elided; if the type
254      * parameter list is present, a space separates the list from the
255      * class name.  If the constructor is declared to throw
256      * exceptions, the parameter list is followed by a space, followed
257      * by the word "{@code throws}" followed by a
258      * comma-separated list of the thrown exception types.
259      *
260      * <p>The only possible modifiers for constructors are the access
261      * modifiers {@code public}, {@code protected} or
262      * {@code private}.  Only one of these may appear, or none if the
263      * constructor has default (package) access.
264      *
265      * @return a string describing this {@code Constructor},
266      * include type parameters
267      *
268      * @since 1.5
269      * @jls 8.8.3. Constructor Modifiers
270      */
271     @Override
toGenericString()272     public String toGenericString() {
273         return sharedToGenericString(Modifier.constructorModifiers(), false);
274     }
275 
276     @Override
specificToGenericStringHeader(StringBuilder sb)277     void specificToGenericStringHeader(StringBuilder sb) {
278         specificToStringHeader(sb);
279     }
280 
281     /**
282      * Uses the constructor represented by this {@code Constructor} object to
283      * create and initialize a new instance of the constructor's
284      * declaring class, with the specified initialization parameters.
285      * Individual parameters are automatically unwrapped to match
286      * primitive formal parameters, and both primitive and reference
287      * parameters are subject to method invocation conversions as necessary.
288      *
289      * <p>If the number of formal parameters required by the underlying constructor
290      * is 0, the supplied {@code initargs} array may be of length 0 or null.
291      *
292      * <p>If the constructor's declaring class is an inner class in a
293      * non-static context, the first argument to the constructor needs
294      * to be the enclosing instance; see section 15.9.3 of
295      * <cite>The Java&trade; Language Specification</cite>.
296      *
297      * <p>If the required access and argument checks succeed and the
298      * instantiation will proceed, the constructor's declaring class
299      * is initialized if it has not already been initialized.
300      *
301      * <p>If the constructor completes normally, returns the newly
302      * created and initialized instance.
303      *
304      * @param initargs array of objects to be passed as arguments to
305      * the constructor call; values of primitive types are wrapped in
306      * a wrapper object of the appropriate type (e.g. a {@code float}
307      * in a {@link java.lang.Float Float})
308      *
309      * @return a new object created by calling the constructor
310      * this object represents
311      *
312      * @exception IllegalAccessException    if this {@code Constructor} object
313      *              is enforcing Java language access control and the underlying
314      *              constructor is inaccessible.
315      * @exception IllegalArgumentException  if the number of actual
316      *              and formal parameters differ; if an unwrapping
317      *              conversion for primitive arguments fails; or if,
318      *              after possible unwrapping, a parameter value
319      *              cannot be converted to the corresponding formal
320      *              parameter type by a method invocation conversion; if
321      *              this constructor pertains to an enum type.
322      * @exception InstantiationException    if the class that declares the
323      *              underlying constructor represents an abstract class.
324      * @exception InvocationTargetException if the underlying constructor
325      *              throws an exception.
326      * @exception ExceptionInInitializerError if the initialization provoked
327      *              by this method fails.
328      */
newInstance(Object .... initargs)329     public T newInstance(Object ... initargs)
330         throws InstantiationException, IllegalAccessException,
331                IllegalArgumentException, InvocationTargetException
332     {
333         if (serializationClass == null) {
334             return newInstance0(initargs);
335         } else {
336             return (T) newInstanceFromSerialization(serializationCtor, serializationClass);
337         }
338     }
339 
340     @FastNative
newInstanceFromSerialization(Class<?> ctorClass, Class<?> allocClass)341     private static native Object newInstanceFromSerialization(Class<?> ctorClass, Class<?> allocClass)
342         throws InstantiationException, IllegalArgumentException, InvocationTargetException;
343 
344     @FastNative
newInstance0(Object... args)345     private native T newInstance0(Object... args) throws InstantiationException,
346             IllegalAccessException, IllegalArgumentException, InvocationTargetException;
347 
348     /**
349      * {@inheritDoc}
350      * @since 1.5
351      */
352     @Override
isVarArgs()353     public boolean isVarArgs() {
354         return super.isVarArgs();
355     }
356 
357     /**
358      * {@inheritDoc}
359      * @jls 13.1 The Form of a Binary
360      * @since 1.5
361      */
362     @Override
isSynthetic()363     public boolean isSynthetic() {
364         return super.isSynthetic();
365     }
366 
367     /**
368      * {@inheritDoc}
369      * @throws NullPointerException  {@inheritDoc}
370      * @since 1.5
371      */
getAnnotation(Class<T> annotationClass)372     public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
373         return super.getAnnotation(annotationClass);
374     }
375 
376     /**
377      * {@inheritDoc}
378      * @since 1.5
379      */
getDeclaredAnnotations()380     public Annotation[] getDeclaredAnnotations()  {
381         return super.getDeclaredAnnotations();
382     }
383 
384     /**
385      * {@inheritDoc}
386      * @since 1.5
387      */
388     @Override
getParameterAnnotations()389     public Annotation[][] getParameterAnnotations() {
390         // Android-changed: This is handled by Executable.
391         return super.getParameterAnnotationsInternal();
392     }
393 }
394