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