Constructor.java 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. /* java.lang.reflect.Constructor - reflection of Java constructors
  2. Copyright (C) 1998, 2001, 2004, 2005 Free Software Foundation, Inc.
  3. This file is part of GNU Classpath.
  4. GNU Classpath is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2, or (at your option)
  7. any later version.
  8. GNU Classpath is distributed in the hope that it will be useful, but
  9. WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with GNU Classpath; see the file COPYING. If not, write to the
  14. Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  15. 02110-1301 USA.
  16. Linking this library statically or dynamically with other modules is
  17. making a combined work based on this library. Thus, the terms and
  18. conditions of the GNU General Public License cover the whole
  19. combination.
  20. As a special exception, the copyright holders of this library give you
  21. permission to link this library with independent modules to produce an
  22. executable, regardless of the license terms of these independent
  23. modules, and to copy and distribute the resulting executable under
  24. terms of your choice, provided that you also meet, for each linked
  25. independent module, the terms and conditions of the license of that
  26. module. An independent module is a module which is not derived from
  27. or based on this library. If you modify this library, you may extend
  28. this exception to your version of the library, but you are not
  29. obligated to do so. If you do not wish to do so, delete this
  30. exception statement from your version. */
  31. package java.lang.reflect;
  32. import gnu.java.lang.ClassHelper;
  33. import gnu.java.lang.CPStringBuilder;
  34. import gnu.java.lang.reflect.MethodSignatureParser;
  35. import java.lang.annotation.Annotation;
  36. /**
  37. * The Constructor class represents a constructor of a class. It also allows
  38. * dynamic creation of an object, via reflection. Invocation on Constructor
  39. * objects knows how to do widening conversions, but throws
  40. * {@link IllegalArgumentException} if a narrowing conversion would be
  41. * necessary. You can query for information on this Constructor regardless
  42. * of location, but construction access may be limited by Java language
  43. * access controls. If you can't do it in the compiler, you can't normally
  44. * do it here either.<p>
  45. *
  46. * <B>Note:</B> This class returns and accepts types as Classes, even
  47. * primitive types; there are Class types defined that represent each
  48. * different primitive type. They are <code>java.lang.Boolean.TYPE,
  49. * java.lang.Byte.TYPE,</code>, also available as <code>boolean.class,
  50. * byte.class</code>, etc. These are not to be confused with the
  51. * classes <code>java.lang.Boolean, java.lang.Byte</code>, etc., which are
  52. * real classes.<p>
  53. *
  54. * Also note that this is not a serializable class. It is entirely feasible
  55. * to make it serializable using the Externalizable interface, but this is
  56. * on Sun, not me.
  57. *
  58. * @author John Keiser
  59. * @author Eric Blake <ebb9@email.byu.edu>
  60. * @see Member
  61. * @see Class
  62. * @see java.lang.Class#getConstructor(Class[])
  63. * @see java.lang.Class#getDeclaredConstructor(Class[])
  64. * @see java.lang.Class#getConstructors()
  65. * @see java.lang.Class#getDeclaredConstructors()
  66. * @since 1.1
  67. * @status updated to 1.4
  68. */
  69. public final class Constructor<T>
  70. extends AccessibleObject
  71. implements GenericDeclaration, Member
  72. {
  73. private static final int CONSTRUCTOR_MODIFIERS
  74. = Modifier.PRIVATE | Modifier.PROTECTED | Modifier.PUBLIC;
  75. private MethodSignatureParser p;
  76. VMConstructor cons;
  77. /**
  78. * This class is uninstantiable outside this package.
  79. */
  80. Constructor(VMConstructor cons)
  81. {
  82. this.cons = cons;
  83. cons.cons = this;
  84. }
  85. private Constructor()
  86. {
  87. }
  88. /**
  89. * Gets the class that declared this constructor.
  90. * @return the class that declared this member
  91. */
  92. public Class<T> getDeclaringClass()
  93. {
  94. // Inescapable as the VM layer is 1.4 based.
  95. @SuppressWarnings("unchecked")
  96. Class<T> declClass = (Class<T>) cons.getDeclaringClass();
  97. return declClass;
  98. }
  99. /**
  100. * Gets the name of this constructor (the non-qualified name of the class
  101. * it was declared in).
  102. * @return the name of this constructor
  103. */
  104. public String getName()
  105. {
  106. return cons.getDeclaringClass().getName();
  107. }
  108. /**
  109. * Gets the modifiers this constructor uses. Use the <code>Modifier</code>
  110. * class to interpret the values. A constructor can only have a subset of the
  111. * following modifiers: public, private, protected.
  112. *
  113. * @return an integer representing the modifiers to this Member
  114. * @see Modifier
  115. */
  116. public int getModifiers()
  117. {
  118. return cons.getModifiersInternal() & CONSTRUCTOR_MODIFIERS;
  119. }
  120. /**
  121. * Return true if this constructor is synthetic, false otherwise.
  122. * A synthetic member is one which is created by the compiler,
  123. * and which does not appear in the user's source code.
  124. * @since 1.5
  125. */
  126. public boolean isSynthetic()
  127. {
  128. return (cons.getModifiersInternal() & Modifier.SYNTHETIC) != 0;
  129. }
  130. /**
  131. * Return true if this is a varargs constructor, that is if
  132. * the constructor takes a variable number of arguments.
  133. * @since 1.5
  134. */
  135. public boolean isVarArgs()
  136. {
  137. return (cons.getModifiersInternal() & Modifier.VARARGS) != 0;
  138. }
  139. /**
  140. * Get the parameter list for this constructor, in declaration order. If the
  141. * constructor takes no parameters, returns a 0-length array (not null).
  142. *
  143. * @return a list of the types of the constructor's parameters
  144. */
  145. public Class<?>[] getParameterTypes()
  146. {
  147. return (Class<?>[]) cons.getParameterTypes();
  148. }
  149. /**
  150. * Get the exception types this constructor says it throws, in no particular
  151. * order. If the constructor has no throws clause, returns a 0-length array
  152. * (not null).
  153. *
  154. * @return a list of the types in the constructor's throws clause
  155. */
  156. public Class<?>[] getExceptionTypes()
  157. {
  158. return (Class<?>[]) cons.getExceptionTypes();
  159. }
  160. /**
  161. * Compare two objects to see if they are semantically equivalent.
  162. * Two Constructors are semantically equivalent if they have the same
  163. * declaring class and the same parameter list. This ignores different
  164. * exception clauses, but since you can't create a Method except through the
  165. * VM, this is just the == relation.
  166. *
  167. * @param o the object to compare to
  168. * @return <code>true</code> if they are equal; <code>false</code> if not.
  169. */
  170. public boolean equals(Object o)
  171. {
  172. return cons.equals(o);
  173. }
  174. /**
  175. * Get the hash code for the Constructor. The Constructor hash code is the
  176. * hash code of the declaring class's name.
  177. *
  178. * @return the hash code for the object
  179. */
  180. public int hashCode()
  181. {
  182. return getName().hashCode();
  183. }
  184. /**
  185. * Get a String representation of the Constructor. A Constructor's String
  186. * representation is "&lt;modifier&gt; &lt;classname&gt;(&lt;paramtypes&gt;)
  187. * throws &lt;exceptions&gt;", where everything after ')' is omitted if
  188. * there are no exceptions.<br> Example:
  189. * <code>public java.io.FileInputStream(java.lang.Runnable)
  190. * throws java.io.FileNotFoundException</code>
  191. *
  192. * @return the String representation of the Constructor
  193. */
  194. public String toString()
  195. {
  196. // 128 is a reasonable buffer initial size for constructor
  197. CPStringBuilder sb = new CPStringBuilder(128);
  198. Modifier.toString(getModifiers(), sb).append(' ');
  199. sb.append(getDeclaringClass().getName()).append('(');
  200. Class[] c = getParameterTypes();
  201. if (c.length > 0)
  202. {
  203. sb.append(ClassHelper.getUserName(c[0]));
  204. for (int i = 1; i < c.length; i++)
  205. sb.append(',').append(ClassHelper.getUserName(c[i]));
  206. }
  207. sb.append(')');
  208. c = getExceptionTypes();
  209. if (c.length > 0)
  210. {
  211. sb.append(" throws ").append(c[0].getName());
  212. for (int i = 1; i < c.length; i++)
  213. sb.append(',').append(c[i].getName());
  214. }
  215. return sb.toString();
  216. }
  217. static <X extends GenericDeclaration>
  218. void addTypeParameters(CPStringBuilder sb, TypeVariable<X>[] typeArgs)
  219. {
  220. if (typeArgs.length == 0)
  221. return;
  222. sb.append('<');
  223. for (int i = 0; i < typeArgs.length; ++i)
  224. {
  225. if (i > 0)
  226. sb.append(',');
  227. sb.append(typeArgs[i]);
  228. }
  229. sb.append("> ");
  230. }
  231. public String toGenericString()
  232. {
  233. CPStringBuilder sb = new CPStringBuilder(128);
  234. Modifier.toString(getModifiers(), sb).append(' ');
  235. addTypeParameters(sb, getTypeParameters());
  236. sb.append(getDeclaringClass().getName()).append('(');
  237. Type[] types = getGenericParameterTypes();
  238. if (types.length > 0)
  239. {
  240. sb.append(types[0]);
  241. for (int i = 1; i < types.length; ++i)
  242. sb.append(',').append(types[i]);
  243. }
  244. sb.append(')');
  245. types = getGenericExceptionTypes();
  246. if (types.length > 0)
  247. {
  248. sb.append(" throws ").append(types[0]);
  249. for (int i = 1; i < types.length; i++)
  250. sb.append(',').append(types[i]);
  251. }
  252. return sb.toString();
  253. }
  254. /**
  255. * Create a new instance by invoking the constructor. Arguments are
  256. * automatically unwrapped and widened, if needed.<p>
  257. *
  258. * If this class is abstract, you will get an
  259. * <code>InstantiationException</code>. If the constructor takes 0
  260. * arguments, you may use null or a 0-length array for <code>args</code>.<p>
  261. *
  262. * If this Constructor enforces access control, your runtime context is
  263. * evaluated, and you may have an <code>IllegalAccessException</code> if
  264. * you could not create this object in similar compiled code. If the class
  265. * is uninitialized, you trigger class initialization, which may end in a
  266. * <code>ExceptionInInitializerError</code>.<p>
  267. *
  268. * Then, the constructor is invoked. If it completes normally, the return
  269. * value will be the new object. If it completes abruptly, the exception is
  270. * wrapped in an <code>InvocationTargetException</code>.
  271. *
  272. * @param args the arguments to the constructor
  273. * @return the newly created object
  274. * @throws IllegalAccessException if the constructor could not normally be
  275. * called by the Java code (i.e. it is not public)
  276. * @throws IllegalArgumentException if the number of arguments is incorrect;
  277. * or if the arguments types are wrong even with a widening
  278. * conversion
  279. * @throws InstantiationException if the class is abstract
  280. * @throws InvocationTargetException if the constructor throws an exception
  281. * @throws ExceptionInInitializerError if construction triggered class
  282. * initialization, which then failed
  283. */
  284. public T newInstance(Object... args)
  285. throws InstantiationException, IllegalAccessException,
  286. InvocationTargetException
  287. {
  288. // Inescapable as the VM layer is 1.4 based.
  289. @SuppressWarnings("unchecked")
  290. T ins = (T) cons.construct(args);
  291. return ins;
  292. }
  293. /**
  294. * Returns an array of <code>TypeVariable</code> objects that represents
  295. * the type variables declared by this constructor, in declaration order.
  296. * An array of size zero is returned if this constructor has no type
  297. * variables.
  298. *
  299. * @return the type variables associated with this constructor.
  300. * @throws GenericSignatureFormatError if the generic signature does
  301. * not conform to the format specified in the Virtual Machine
  302. * specification, version 3.
  303. * @since 1.5
  304. */
  305. public TypeVariable<Constructor<T>>[] getTypeParameters()
  306. {
  307. if (p == null)
  308. {
  309. String sig = cons.getSignature();
  310. if (sig == null)
  311. return new TypeVariable[0];
  312. p = new MethodSignatureParser(this, sig);
  313. }
  314. return p.getTypeParameters();
  315. }
  316. /**
  317. * Returns an array of <code>Type</code> objects that represents
  318. * the exception types declared by this constructor, in declaration order.
  319. * An array of size zero is returned if this constructor declares no
  320. * exceptions.
  321. *
  322. * @return the exception types declared by this constructor.
  323. * @throws GenericSignatureFormatError if the generic signature does
  324. * not conform to the format specified in the Virtual Machine
  325. * specification, version 3.
  326. * @since 1.5
  327. */
  328. public Type[] getGenericExceptionTypes()
  329. {
  330. if (p == null)
  331. {
  332. String sig = cons.getSignature();
  333. if (sig == null)
  334. return getExceptionTypes();
  335. p = new MethodSignatureParser(this, sig);
  336. }
  337. return p.getGenericExceptionTypes();
  338. }
  339. /**
  340. * Returns an array of <code>Type</code> objects that represents
  341. * the parameter list for this constructor, in declaration order.
  342. * An array of size zero is returned if this constructor takes no
  343. * parameters.
  344. *
  345. * @return a list of the types of the constructor's parameters
  346. * @throws GenericSignatureFormatError if the generic signature does
  347. * not conform to the format specified in the Virtual Machine
  348. * specification, version 3.
  349. * @since 1.5
  350. */
  351. public Type[] getGenericParameterTypes()
  352. {
  353. if (p == null)
  354. {
  355. String sig = cons.getSignature();
  356. if (sig == null)
  357. return getParameterTypes();
  358. p = new MethodSignatureParser(this, sig);
  359. }
  360. return p.getGenericParameterTypes();
  361. }
  362. /**
  363. * <p>
  364. * Return an array of arrays representing the annotations on each
  365. * of the constructor's parameters. The outer array is aligned against
  366. * the parameters of the constructors and is thus equal in length to
  367. * the number of parameters (thus having a length zero if there are none).
  368. * Each array element in the outer array contains an inner array which
  369. * holds the annotations. This array has a length of zero if the parameter
  370. * has no annotations.
  371. * </p>
  372. * <p>
  373. * The returned annotations are serialized. Changing the annotations has
  374. * no affect on the return value of future calls to this method.
  375. * </p>
  376. *
  377. * @return an array of arrays which represents the annotations used on the
  378. * parameters of this constructor. The order of the array elements
  379. * matches the declaration order of the parameters.
  380. * @since 1.5
  381. */
  382. public Annotation[][] getParameterAnnotations()
  383. {
  384. return cons.getParameterAnnotations();
  385. }
  386. /**
  387. * Returns the element's annotation for the specified annotation type,
  388. * or <code>null</code> if no such annotation exists.
  389. *
  390. * @param annotationClass the type of annotation to look for.
  391. * @return this element's annotation for the specified type, or
  392. * <code>null</code> if no such annotation exists.
  393. * @throws NullPointerException if the annotation class is <code>null</code>.
  394. */
  395. public <T extends Annotation> T getAnnotation(Class<T> annotationClass)
  396. {
  397. // Inescapable as the VM layer is 1.4 based.
  398. @SuppressWarnings("unchecked")
  399. T ann = (T) cons.getAnnotation(annotationClass);
  400. return ann;
  401. }
  402. /**
  403. * Returns all annotations directly defined by the element. If there are
  404. * no annotations directly associated with the element, then a zero-length
  405. * array will be returned. The returned array may be modified by the client
  406. * code, but this will have no effect on the annotation content of this
  407. * class, and hence no effect on the return value of this method for
  408. * future callers.
  409. *
  410. * @return the annotations directly defined by the element.
  411. * @since 1.5
  412. */
  413. public Annotation[] getDeclaredAnnotations()
  414. {
  415. return cons.getDeclaredAnnotations();
  416. }
  417. }