Constructor.java 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. /* java.lang.reflect.Constructor - reflection of Java constructors
  2. Copyright (C) 1998, 1999, 2000, 2001, 2003, 2004, 2005, 2006, 2007
  3. Free Software Foundation, Inc.
  4. This file is part of GNU Classpath.
  5. GNU Classpath is free software; you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation; either version 2, or (at your option)
  8. any later version.
  9. GNU Classpath is distributed in the hope that it will be useful, but
  10. WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with GNU Classpath; see the file COPYING. If not, write to the
  15. Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  16. 02110-1301 USA.
  17. Linking this library statically or dynamically with other modules is
  18. making a combined work based on this library. Thus, the terms and
  19. conditions of the GNU General Public License cover the whole
  20. combination.
  21. As a special exception, the copyright holders of this library give you
  22. permission to link this library with independent modules to produce an
  23. executable, regardless of the license terms of these independent
  24. modules, and to copy and distribute the resulting executable under
  25. terms of your choice, provided that you also meet, for each linked
  26. independent module, the terms and conditions of the license of that
  27. module. An independent module is a module which is not derived from
  28. or based on this library. If you modify this library, you may extend
  29. this exception to your version of the library, but you are not
  30. obligated to do so. If you do not wish to do so, delete this
  31. exception statement from your version. */
  32. package java.lang.reflect;
  33. import gnu.java.lang.reflect.MethodSignatureParser;
  34. import java.lang.annotation.Annotation;
  35. /**
  36. * The Constructor class represents a constructor of a class. It also allows
  37. * dynamic creation of an object, via reflection. Invocation on Constructor
  38. * objects knows how to do widening conversions, but throws
  39. * {@link IllegalArgumentException} if a narrowing conversion would be
  40. * necessary. You can query for information on this Constructor regardless
  41. * of location, but construction access may be limited by Java language
  42. * access controls. If you can't do it in the compiler, you can't normally
  43. * do it here either.<p>
  44. *
  45. * <B>Note:</B> This class returns and accepts types as Classes, even
  46. * primitive types; there are Class types defined that represent each
  47. * different primitive type. They are <code>java.lang.Boolean.TYPE,
  48. * java.lang.Byte.TYPE,</code>, also available as <code>boolean.class,
  49. * byte.class</code>, etc. These are not to be confused with the
  50. * classes <code>java.lang.Boolean, java.lang.Byte</code>, etc., which are
  51. * real classes.<p>
  52. *
  53. * Also note that this is not a serializable class. It is entirely feasible
  54. * to make it serializable using the Externalizable interface, but this is
  55. * on Sun, not me.
  56. *
  57. * @author John Keiser
  58. * @author Eric Blake <ebb9@email.byu.edu>
  59. * @author Tom Tromey <tromey@redhat.com>
  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> extends AccessibleObject
  70. implements Member, GenericDeclaration
  71. {
  72. private static final int CONSTRUCTOR_MODIFIERS
  73. = Modifier.PRIVATE | Modifier.PROTECTED | Modifier.PUBLIC;
  74. /**
  75. * This class is uninstantiable except from native code.
  76. */
  77. private Constructor ()
  78. {
  79. }
  80. /**
  81. * Gets the class that declared this constructor.
  82. * @return the class that declared this member
  83. */
  84. public Class<T> getDeclaringClass ()
  85. {
  86. return declaringClass;
  87. }
  88. /**
  89. * Gets the name of this constructor (the non-qualified name of the class
  90. * it was declared in).
  91. * @return the name of this constructor
  92. */
  93. public String getName()
  94. {
  95. return declaringClass.getName();
  96. }
  97. /**
  98. * Return the raw modifiers for this constructor. In particular
  99. * this will include the synthetic and varargs bits.
  100. * @return the constructor's modifiers
  101. */
  102. private native int getModifiersInternal();
  103. /**
  104. * Gets the modifiers this constructor uses. Use the <code>Modifier</code>
  105. * class to interpret the values. A constructor can only have a subset of the
  106. * following modifiers: public, private, protected.
  107. *
  108. * @return an integer representing the modifiers to this Member
  109. * @see Modifier
  110. */
  111. public int getModifiers ()
  112. {
  113. return getModifiersInternal() & CONSTRUCTOR_MODIFIERS;
  114. }
  115. /**
  116. * Return true if this constructor is synthetic, false otherwise.
  117. * A synthetic member is one which is created by the compiler,
  118. * and which does not appear in the user's source code.
  119. * @since 1.5
  120. */
  121. public boolean isSynthetic()
  122. {
  123. return (getModifiersInternal() & Modifier.SYNTHETIC) != 0;
  124. }
  125. /**
  126. * Return true if this is a varargs constructor, that is if
  127. * the constructor takes a variable number of arguments.
  128. * @since 1.5
  129. */
  130. public boolean isVarArgs()
  131. {
  132. return (getModifiersInternal() & Modifier.VARARGS) != 0;
  133. }
  134. /**
  135. * Get the parameter list for this constructor, in declaration order. If the
  136. * constructor takes no parameters, returns a 0-length array (not null).
  137. *
  138. * @return a list of the types of the constructor's parameters
  139. */
  140. public Class<?>[] getParameterTypes ()
  141. {
  142. if (parameter_types == null)
  143. getType ();
  144. return (Class<?>[]) parameter_types.clone();
  145. }
  146. /**
  147. * Get the exception types this constructor says it throws, in no particular
  148. * order. If the constructor has no throws clause, returns a 0-length array
  149. * (not null).
  150. *
  151. * @return a list of the types in the constructor's throws clause
  152. */
  153. public Class<?>[] getExceptionTypes ()
  154. {
  155. if (exception_types == null)
  156. getType();
  157. return (Class<?>[]) exception_types.clone();
  158. }
  159. /**
  160. * Compare two objects to see if they are semantically equivalent.
  161. * Two Constructors are semantically equivalent if they have the same
  162. * declaring class and the same parameter list.
  163. *
  164. * @param o the object to compare to
  165. * @return <code>true</code> if they are equal; <code>false</code> if not.
  166. */
  167. public boolean equals (Object obj)
  168. {
  169. if (! (obj instanceof Constructor))
  170. return false;
  171. Constructor c = (Constructor) obj;
  172. return declaringClass == c.declaringClass && offset == c.offset;
  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 declaringClass.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. if (parameter_types == null)
  197. getType ();
  198. StringBuffer b = new StringBuffer ();
  199. int mods = getModifiers();
  200. if (mods != 0)
  201. {
  202. Modifier.toString(mods, b);
  203. b.append(" ");
  204. }
  205. Method.appendClassName (b, declaringClass);
  206. b.append("(");
  207. for (int i = 0; i < parameter_types.length; ++i)
  208. {
  209. Method.appendClassName (b, parameter_types[i]);
  210. if (i < parameter_types.length - 1)
  211. b.append(",");
  212. }
  213. b.append(")");
  214. return b.toString();
  215. }
  216. static <X extends GenericDeclaration>
  217. void addTypeParameters(StringBuilder sb, TypeVariable<X>[] typeArgs)
  218. {
  219. if (typeArgs.length == 0)
  220. return;
  221. sb.append('<');
  222. for (int i = 0; i < typeArgs.length; ++i)
  223. {
  224. if (i > 0)
  225. sb.append(',');
  226. sb.append(typeArgs[i]);
  227. }
  228. sb.append("> ");
  229. }
  230. public String toGenericString()
  231. {
  232. StringBuilder sb = new StringBuilder(128);
  233. Modifier.toString(getModifiers(), sb).append(' ');
  234. addTypeParameters(sb, getTypeParameters());
  235. sb.append(getDeclaringClass().getName()).append('(');
  236. Type[] types = getGenericParameterTypes();
  237. if (types.length > 0)
  238. {
  239. sb.append(types[0]);
  240. for (int i = 1; i < types.length; ++i)
  241. sb.append(',').append(types[i]);
  242. }
  243. sb.append(')');
  244. types = getGenericExceptionTypes();
  245. if (types.length > 0)
  246. {
  247. sb.append(" throws ").append(types[0]);
  248. for (int i = 1; i < types.length; i++)
  249. sb.append(',').append(types[i]);
  250. }
  251. return sb.toString();
  252. }
  253. /**
  254. * Create a new instance by invoking the constructor. Arguments are
  255. * automatically unwrapped and widened, if needed.<p>
  256. *
  257. * If this class is abstract, you will get an
  258. * <code>InstantiationException</code>. If the constructor takes 0
  259. * arguments, you may use null or a 0-length array for <code>args</code>.<p>
  260. *
  261. * If this Constructor enforces access control, your runtime context is
  262. * evaluated, and you may have an <code>IllegalAccessException</code> if
  263. * you could not create this object in similar compiled code. If the class
  264. * is uninitialized, you trigger class initialization, which may end in a
  265. * <code>ExceptionInInitializerError</code>.<p>
  266. *
  267. * Then, the constructor is invoked. If it completes normally, the return
  268. * value will be the new object. If it completes abruptly, the exception is
  269. * wrapped in an <code>InvocationTargetException</code>.
  270. *
  271. * @param args the arguments to the constructor
  272. * @return the newly created object
  273. * @throws IllegalAccessException if the constructor could not normally be
  274. * called by the Java code (i.e. it is not public)
  275. * @throws IllegalArgumentException if the number of arguments is incorrect;
  276. * or if the arguments types are wrong even with a widening
  277. * conversion
  278. * @throws InstantiationException if the class is abstract
  279. * @throws InvocationTargetException if the constructor throws an exception
  280. * @throws ExceptionInInitializerError if construction triggered class
  281. * initialization, which then failed
  282. */
  283. public native T newInstance (Object... args)
  284. throws InstantiationException, IllegalAccessException,
  285. IllegalArgumentException, InvocationTargetException;
  286. /**
  287. * Returns an array of <code>TypeVariable</code> objects that represents
  288. * the type variables declared by this constructor, in declaration order.
  289. * An array of size zero is returned if this constructor has no type
  290. * variables.
  291. *
  292. * @return the type variables associated with this constructor.
  293. * @throws GenericSignatureFormatError if the generic signature does
  294. * not conform to the format specified in the Virtual Machine
  295. * specification, version 3.
  296. * @since 1.5
  297. */
  298. public TypeVariable<Constructor<T>>[] getTypeParameters()
  299. {
  300. String sig = getSignature();
  301. if (sig == null)
  302. return new TypeVariable[0];
  303. MethodSignatureParser p = new MethodSignatureParser(this, sig);
  304. return p.getTypeParameters();
  305. }
  306. /**
  307. * Return the String in the Signature attribute for this constructor. If there
  308. * is no Signature attribute, return null.
  309. */
  310. private native String getSignature();
  311. /**
  312. * Returns an array of <code>Type</code> objects that represents
  313. * the exception types declared by this constructor, in declaration order.
  314. * An array of size zero is returned if this constructor declares no
  315. * exceptions.
  316. *
  317. * @return the exception types declared by this constructor.
  318. * @throws GenericSignatureFormatError if the generic signature does
  319. * not conform to the format specified in the Virtual Machine
  320. * specification, version 3.
  321. * @since 1.5
  322. */
  323. public Type[] getGenericExceptionTypes()
  324. {
  325. String sig = getSignature();
  326. if (sig == null)
  327. return getExceptionTypes();
  328. MethodSignatureParser p = new MethodSignatureParser(this, sig);
  329. return p.getGenericExceptionTypes();
  330. }
  331. /**
  332. * Returns an array of <code>Type</code> objects that represents
  333. * the parameter list for this constructor, in declaration order.
  334. * An array of size zero is returned if this constructor takes no
  335. * parameters.
  336. *
  337. * @return a list of the types of the constructor's parameters
  338. * @throws GenericSignatureFormatError if the generic signature does
  339. * not conform to the format specified in the Virtual Machine
  340. * specification, version 3.
  341. * @since 1.5
  342. */
  343. public Type[] getGenericParameterTypes()
  344. {
  345. String sig = getSignature();
  346. if (sig == null)
  347. return getParameterTypes();
  348. MethodSignatureParser p = new MethodSignatureParser(this, sig);
  349. return p.getGenericParameterTypes();
  350. }
  351. public <T extends Annotation> T getAnnotation(Class<T> annoClass)
  352. {
  353. Annotation[] annos = getDeclaredAnnotations();
  354. for (int i = 0; i < annos.length; ++i)
  355. if (annos[i].annotationType() == annoClass)
  356. return (T) annos[i];
  357. return null;
  358. }
  359. public Annotation[] getDeclaredAnnotations()
  360. {
  361. Annotation[] result = getDeclaredAnnotationsInternal();
  362. if (result == null)
  363. result = new Annotation[0];
  364. return result;
  365. }
  366. public Annotation[][] getParameterAnnotations()
  367. {
  368. // FIXME: should check that we have the right number
  369. // of parameters ...?
  370. Annotation[][] result = getParameterAnnotationsInternal();
  371. if (result == null)
  372. result = new Annotation[0][0];
  373. return result;
  374. }
  375. private native Annotation[] getDeclaredAnnotationsInternal();
  376. private native Annotation[][] getParameterAnnotationsInternal();
  377. // Update cached values from method descriptor in class.
  378. private native void getType ();
  379. // Declaring class.
  380. private Class<T> declaringClass;
  381. // Exception types.
  382. private Class[] exception_types;
  383. // Parameter types.
  384. private Class[] parameter_types;
  385. // Offset in bytes from the start of declaringClass's methods array.
  386. private int offset;
  387. }