001: /*
002: * @(#)Constructor.java 1.34 06/10/10
003: *
004: * Copyright 1990-2006 Sun Microsystems, Inc. All Rights Reserved.
005: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
006: *
007: * This program is free software; you can redistribute it and/or
008: * modify it under the terms of the GNU General Public License version
009: * 2 only, as published by the Free Software Foundation.
010: *
011: * This program is distributed in the hope that it will be useful, but
012: * WITHOUT ANY WARRANTY; without even the implied warranty of
013: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
014: * General Public License version 2 for more details (a copy is
015: * included at /legal/license.txt).
016: *
017: * You should have received a copy of the GNU General Public License
018: * version 2 along with this work; if not, write to the Free Software
019: * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
020: * 02110-1301 USA
021: *
022: * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
023: * Clara, CA 95054 or visit www.sun.com if you need additional
024: * information or have any questions.
025: *
026: */
027:
028: package java.lang.reflect;
029:
030: import sun.misc.CVM;
031:
032: /**
033: * <code>Constructor</code> provides information about, and access to, a single
034: * constructor for a class.
035: *
036: * <p><code>Constructor</code> permits widening conversions to occur when matching the
037: * actual parameters to newInstance() with the underlying
038: * constructor's formal parameters, but throws an
039: * <code>IllegalArgumentException</code> if a narrowing conversion would occur.
040: *
041: * @see Member
042: * @see java.lang.Class
043: * @see java.lang.Class#getConstructors()
044: * @see java.lang.Class#getConstructor(Class[])
045: * @see java.lang.Class#getDeclaredConstructors()
046: *
047: * @author Nakul Saraiya
048: */
049: public final class Constructor extends AccessibleObject implements
050: Member {
051:
052: private Class clazz;
053: private int slot;
054: private Class[] parameterTypes;
055: private Class[] exceptionTypes;
056: private int modifiers;
057:
058: /**
059: * Constructor. Only the Java Virtual Machine may construct
060: * a Constructor.
061: */
062: private Constructor() {
063: }
064:
065: /**
066: * Returns the <code>Class</code> object representing the class that declares
067: * the constructor represented by this <code>Constructor</code> object.
068: */
069: public Class getDeclaringClass() {
070: return clazz;
071: }
072:
073: /**
074: * Returns the name of this constructor, as a string. This is
075: * always the same as the simple name of the constructor's declaring
076: * class.
077: */
078: public String getName() {
079: return getDeclaringClass().getName();
080: }
081:
082: /**
083: * Returns the Java language modifiers for the constructor
084: * represented by this <code>Constructor</code> object, as an integer. The
085: * <code>Modifier</code> class should be used to decode the modifiers.
086: *
087: * @see Modifier
088: */
089: public int getModifiers() {
090: return modifiers;
091: }
092:
093: /**
094: * Returns an array of <code>Class</code> objects that represent the formal
095: * parameter types, in declaration order, of the constructor
096: * represented by this <code>Constructor</code> object. Returns an array of
097: * length 0 if the underlying constructor takes no parameters.
098: *
099: * @return the parameter types for the constructor this object
100: * represents
101: */
102: public Class[] getParameterTypes() {
103: return Method.copy(parameterTypes);
104: }
105:
106: /**
107: * Returns an array of <code>Class</code> objects that represent the types of
108: * of exceptions declared to be thrown by the underlying constructor
109: * represented by this <code>Constructor</code> object. Returns an array of
110: * length 0 if the constructor declares no exceptions in its <code>throws</code> clause.
111: *
112: * @return the exception types declared as being thrown by the
113: * constructor this object represents
114: */
115: public Class[] getExceptionTypes() {
116: return Method.copy(exceptionTypes);
117: }
118:
119: /**
120: * Compares this <code>Constructor</code> against the specified object.
121: * Returns true if the objects are the same. Two <code>Constructor</code> objects are
122: * the same if they were declared by the same class and have the
123: * same formal parameter types.
124: */
125: public boolean equals(Object obj) {
126: if (obj != null && obj instanceof Constructor) {
127: Constructor other = (Constructor) obj;
128: if (getDeclaringClass() == other.getDeclaringClass()) {
129: /* Avoid unnecessary cloning */
130: Class[] params1 = parameterTypes;
131: Class[] params2 = other.parameterTypes;
132: if (params1.length == params2.length) {
133: for (int i = 0; i < params1.length; i++) {
134: if (params1[i] != params2[i])
135: return false;
136: }
137: return true;
138: }
139: }
140: }
141: return false;
142: }
143:
144: /**
145: * Returns a hashcode for this <code>Constructor</code>. The hashcode is
146: * the same as the hashcode for the underlying constructor's
147: * declaring class name.
148: */
149: public int hashCode() {
150: return getDeclaringClass().getName().hashCode();
151: }
152:
153: /**
154: * Returns a string describing this <code>Constructor</code>. The string is
155: * formatted as the constructor access modifiers, if any,
156: * followed by the fully-qualified name of the declaring class,
157: * followed by a parenthesized, comma-separated list of the
158: * constructor's formal parameter types. For example:
159: * <pre>
160: * public java.util.Hashtable(int,float)
161: * </pre>
162: *
163: * <p>The only possible modifiers for constructors are the access
164: * modifiers <tt>public</tt>, <tt>protected</tt> or
165: * <tt>private</tt>. Only one of these may appear, or none if the
166: * constructor has default (package) access.
167: */
168: public String toString() {
169: try {
170: StringBuffer sb = new StringBuffer();
171: int mod = getModifiers();
172: if (mod != 0) {
173: sb.append(Modifier.toString(mod) + " ");
174: }
175: sb.append(Field.getTypeName(getDeclaringClass()));
176: sb.append("(");
177: Class[] params = parameterTypes; // avoid clone
178: for (int j = 0; j < params.length; j++) {
179: sb.append(Field.getTypeName(params[j]));
180: if (j < (params.length - 1))
181: sb.append(",");
182: }
183: sb.append(")");
184: Class[] exceptions = exceptionTypes; // avoid clone
185: if (exceptions.length > 0) {
186: sb.append(" throws ");
187: for (int k = 0; k < exceptions.length; k++) {
188: sb.append(exceptions[k].getName());
189: if (k < (exceptions.length - 1))
190: sb.append(",");
191: }
192: }
193: return sb.toString();
194: } catch (Exception e) {
195: return "<" + e + ">";
196: }
197: }
198:
199: /** An internal class to be able to distinguish between an
200: IllegalArgumentException because of incorrectly-typed objects in
201: the argument array to Constructor.newInstance() and one thrown
202: by the invoked method. NOTE: do not change the name of this
203: class as it is referenced by name in reflect.c, utils.c and
204: elsewhere. */
205: private static class ArgumentException extends Exception {
206: }
207:
208: /** An internal class to be able to distinguish between an
209: IllegalAccessException because of an invalid attempt to invoke a
210: protected or private method in Constructor.newInstance() and one
211: thrown by the invoked method. NOTE: do not change the name of
212: this class as it is referenced by name in reflect.c, utils.c and
213: elsewhere. */
214: private static class AccessException extends Exception {
215: }
216:
217: /**
218: * Uses the constructor represented by this <code>Constructor</code> object to
219: * create and initialize a new instance of the constructor's
220: * declaring class, with the specified initialization parameters.
221: * Individual parameters are automatically unwrapped to match
222: * primitive formal parameters, and both primitive and reference
223: * parameters are subject to method invocation conversions as necessary.
224: *
225: * <p>If the number of formal parameters required by the underlying constructor
226: * is 0, the supplied <code>initargs</code> array may be of length 0 or null.
227: *
228: * <p>If the required access and argument checks succeed and the
229: * instantiation will proceed, the constructor's declaring class
230: * is initialized if it has not already been initialized.
231: *
232: * <p>If the constructor completes normally, returns the newly
233: * created and initialized instance.
234: *
235: * @param initargs array of objects to be passed as arguments to
236: * the constructor call; values of primitive types are wrapped in
237: * a wrapper object of the appropriate type (e.g. a <tt>float</tt>
238: * in a {@link java.lang.Float Float})
239: *
240: * @return a new object created by calling the constructor
241: * this object represents
242: *
243: * @exception IllegalAccessException if this <code>Constructor</code> object
244: * enforces Java language access control and the underlying
245: * constructor is inaccessible.
246: * @exception IllegalArgumentException if the number of actual
247: * and formal parameters differ; if an unwrapping
248: * conversion for primitive arguments fails; or if,
249: * after possible unwrapping, a parameter value
250: * cannot be converted to the corresponding formal
251: * parameter type by a method invocation conversion.
252: * @exception InstantiationException if the class that declares the
253: * underlying constructor represents an abstract class.
254: * @exception InvocationTargetException if the underlying constructor
255: * throws an exception.
256: * @exception ExceptionInInitializerError if the initialization provoked
257: * by this method fails.
258: */
259: public Object newInstance(Object[] initargs)
260: throws InstantiationException, IllegalAccessException,
261: IllegalArgumentException, InvocationTargetException {
262: /* Null pointer is acceptable for args if no arguments to method */
263: if (parameterTypes.length == 0) {
264: if ((initargs != null) && (initargs.length != 0))
265: throw new IllegalArgumentException(
266: "wrong number of arguments");
267: } else {
268: if ((initargs == null)
269: || (initargs.length != parameterTypes.length))
270: throw new IllegalArgumentException(
271: "wrong number of arguments");
272: }
273:
274: /* %comment: rt038 */
275:
276: CVM.setContextArtificial();
277:
278: Object res = allocateUninitializedObject(clazz);
279: // If result is null this means the allocation threw an
280: // exception, so we will never call invokeConstructor with a
281: // null object pointer.
282: try {
283: invokeConstructor(res, initargs);
284: } catch (ArgumentException e) {
285: throw new IllegalArgumentException(
286: "wrong object type, or unwrapping conversion failed");
287: } catch (AccessException e) {
288: throw new IllegalAccessException();
289: } catch (Throwable e) {
290: throw new InvocationTargetException(e);
291: }
292: return res;
293: }
294:
295: private static native Object allocateUninitializedObject(Class clazz)
296: throws InstantiationException, IllegalAccessException;
297:
298: private native void invokeConstructor(Object obj, Object[] args)
299: throws ArgumentException, AccessException, Exception;
300: }
|