Class.java 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431
  1. /* Class.java -- Representation of a Java class.
  2. Copyright (C) 1998, 1999, 2000, 2002, 2003, 2004, 2005, 2006, 2007
  3. Free Software Foundation
  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;
  33. import gnu.java.lang.reflect.ClassSignatureParser;
  34. import java.io.InputStream;
  35. import java.io.Serializable;
  36. import java.lang.annotation.Annotation;
  37. import java.lang.reflect.Constructor;
  38. import java.lang.reflect.Field;
  39. import java.lang.reflect.GenericDeclaration;
  40. import java.lang.reflect.InvocationTargetException;
  41. import java.lang.reflect.Member;
  42. import java.lang.reflect.Method;
  43. import java.lang.reflect.Type;
  44. import java.lang.reflect.TypeVariable;
  45. import java.net.URL;
  46. import java.security.AccessController;
  47. import java.security.PrivilegedAction;
  48. import java.security.ProtectionDomain;
  49. import java.util.ArrayList;
  50. import java.util.Arrays;
  51. import java.util.LinkedHashSet;
  52. import java.util.HashMap;
  53. import java.util.Collection;
  54. import java.lang.reflect.AnnotatedElement;
  55. import java.lang.annotation.Annotation;
  56. import java.lang.annotation.Inherited;
  57. import java.lang.reflect.AccessibleObject;
  58. /**
  59. * A Class represents a Java type. There will never be multiple Class
  60. * objects with identical names and ClassLoaders. Primitive types, array
  61. * types, and void also have a Class object.
  62. *
  63. * <p>Arrays with identical type and number of dimensions share the same class.
  64. * The array class ClassLoader is the same as the ClassLoader of the element
  65. * type of the array (which can be null to indicate the bootstrap classloader).
  66. * The name of an array class is <code>[&lt;signature format&gt;;</code>.
  67. * <p> For example,
  68. * String[]'s class is <code>[Ljava.lang.String;</code>. boolean, byte,
  69. * short, char, int, long, float and double have the "type name" of
  70. * Z,B,S,C,I,J,F,D for the purposes of array classes. If it's a
  71. * multidimensioned array, the same principle applies:
  72. * <code>int[][][]</code> == <code>[[[I</code>.
  73. *
  74. * <p>There is no public constructor - Class objects are obtained only through
  75. * the virtual machine, as defined in ClassLoaders.
  76. *
  77. * @serialData Class objects serialize specially:
  78. * <code>TC_CLASS ClassDescriptor</code>. For more serialization information,
  79. * see {@link ObjectStreamClass}.
  80. *
  81. * @author John Keiser
  82. * @author Eric Blake (ebb9@email.byu.edu)
  83. * @author Tom Tromey (tromey@cygnus.com)
  84. * @since 1.0
  85. * @see ClassLoader
  86. */
  87. public final class Class<T>
  88. implements Type, AnnotatedElement, GenericDeclaration, Serializable
  89. {
  90. /**
  91. * Class is non-instantiable from Java code; only the VM can create
  92. * instances of this class.
  93. */
  94. private Class ()
  95. {
  96. }
  97. // Initialize the class.
  98. private native void initializeClass ();
  99. // finalization
  100. protected native void finalize () throws Throwable;
  101. /**
  102. * Use the classloader of the current class to load, link, and initialize
  103. * a class. This is equivalent to your code calling
  104. * <code>Class.forName(name, true, getClass().getClassLoader())</code>.
  105. *
  106. * @param name the name of the class to find
  107. * @return the Class object representing the class
  108. * @throws ClassNotFoundException if the class was not found by the
  109. * classloader
  110. * @throws LinkageError if linking the class fails
  111. * @throws ExceptionInInitializerError if the class loads, but an exception
  112. * occurs during initialization
  113. */
  114. public static native Class<?> forName (String className)
  115. throws ClassNotFoundException;
  116. // A private internal method that is called by compiler-generated code.
  117. private static Class forName (String className, Class caller)
  118. throws ClassNotFoundException
  119. {
  120. return forName(className, true, caller.getClassLoaderInternal());
  121. }
  122. /**
  123. * Use the specified classloader to load and link a class. If the loader
  124. * is null, this uses the bootstrap class loader (provide the security
  125. * check succeeds). Unfortunately, this method cannot be used to obtain
  126. * the Class objects for primitive types or for void, you have to use
  127. * the fields in the appropriate java.lang wrapper classes.
  128. *
  129. * <p>Calls <code>classloader.loadclass(name, initialize)</code>.
  130. *
  131. * @param name the name of the class to find
  132. * @param initialize whether or not to initialize the class at this time
  133. * @param classloader the classloader to use to find the class; null means
  134. * to use the bootstrap class loader
  135. * @throws ClassNotFoundException if the class was not found by the
  136. * classloader
  137. * @throws LinkageError if linking the class fails
  138. * @throws ExceptionInInitializerError if the class loads, but an exception
  139. * occurs during initialization
  140. * @throws SecurityException if the <code>classloader</code> argument
  141. * is <code>null</code> and the caller does not have the
  142. * <code>RuntimePermission("getClassLoader")</code> permission
  143. * @see ClassLoader
  144. * @since 1.2
  145. */
  146. public static native Class<?> forName (String className, boolean initialize,
  147. ClassLoader loader)
  148. throws ClassNotFoundException;
  149. /**
  150. * Get all the public member classes and interfaces declared in this
  151. * class or inherited from superclasses. This returns an array of length
  152. * 0 if there are no member classes, including for primitive types. A
  153. * security check may be performed, with
  154. * <code>checkMemberAccess(this, Member.PUBLIC)</code> as well as
  155. * <code>checkPackageAccess</code> both having to succeed.
  156. *
  157. * @return all public member classes in this class
  158. * @throws SecurityException if the security check fails
  159. * @since 1.1
  160. */
  161. public Class<?>[] getClasses()
  162. {
  163. memberAccessCheck(Member.PUBLIC);
  164. return internalGetClasses();
  165. }
  166. /**
  167. * Like <code>getClasses()</code> but without the security checks.
  168. */
  169. private Class<?>[] internalGetClasses()
  170. {
  171. ArrayList<Class> list = new ArrayList<Class>();
  172. list.addAll(Arrays.asList(getDeclaredClasses(true)));
  173. Class superClass = getSuperclass();
  174. if (superClass != null)
  175. list.addAll(Arrays.asList(superClass.internalGetClasses()));
  176. return list.toArray(new Class<?>[list.size()]);
  177. }
  178. /**
  179. * Get the ClassLoader that loaded this class. If the class was loaded
  180. * by the bootstrap classloader, this method will return null.
  181. * If there is a security manager, and the caller's class loader is not
  182. * an ancestor of the requested one, a security check of
  183. * <code>RuntimePermission("getClassLoader")</code>
  184. * must first succeed. Primitive types and void return null.
  185. *
  186. * @return the ClassLoader that loaded this class
  187. * @throws SecurityException if the security check fails
  188. * @see ClassLoader
  189. * @see RuntimePermission
  190. */
  191. public native ClassLoader getClassLoader ();
  192. // A private internal method that is called by compiler-generated code.
  193. private final native ClassLoader getClassLoader (Class caller);
  194. /**
  195. * Internal method that circumvents the usual security checks when
  196. * getting the class loader.
  197. */
  198. private native ClassLoader getClassLoaderInternal ();
  199. /**
  200. * If this is an array, get the Class representing the type of array.
  201. * Examples: "[[Ljava.lang.String;" would return "[Ljava.lang.String;", and
  202. * calling getComponentType on that would give "java.lang.String". If
  203. * this is not an array, returns null.
  204. *
  205. * @return the array type of this class, or null
  206. * @see Array
  207. * @since 1.1
  208. */
  209. public native Class<?> getComponentType ();
  210. /**
  211. * Get a public constructor declared in this class. If the constructor takes
  212. * no argument, an array of zero elements and null are equivalent for the
  213. * types argument. A security check may be performed, with
  214. * <code>checkMemberAccess(this, Member.PUBLIC)</code> as well as
  215. * <code>checkPackageAccess</code> both having to succeed.
  216. *
  217. * @param types the type of each parameter
  218. * @return the constructor
  219. * @throws NoSuchMethodException if the constructor does not exist
  220. * @throws SecurityException if the security check fails
  221. * @see #getConstructors()
  222. * @since 1.1
  223. */
  224. public native Constructor<T> getConstructor(Class<?>... args)
  225. throws NoSuchMethodException;
  226. /**
  227. * Get all the public constructors of this class. This returns an array of
  228. * length 0 if there are no constructors, including for primitive types,
  229. * arrays, and interfaces. It does, however, include the default
  230. * constructor if one was supplied by the compiler. A security check may
  231. * be performed, with <code>checkMemberAccess(this, Member.PUBLIC)</code>
  232. * as well as <code>checkPackageAccess</code> both having to succeed.
  233. *
  234. * @return all public constructors in this class
  235. * @throws SecurityException if the security check fails
  236. * @since 1.1
  237. */
  238. public Constructor<?>[] getConstructors()
  239. {
  240. memberAccessCheck(Member.PUBLIC);
  241. return getDeclaredConstructors(true);
  242. }
  243. /**
  244. * Get a constructor declared in this class. If the constructor takes no
  245. * argument, an array of zero elements and null are equivalent for the
  246. * types argument. A security check may be performed, with
  247. * <code>checkMemberAccess(this, Member.DECLARED)</code> as well as
  248. * <code>checkPackageAccess</code> both having to succeed.
  249. *
  250. * @param types the type of each parameter
  251. * @return the constructor
  252. * @throws NoSuchMethodException if the constructor does not exist
  253. * @throws SecurityException if the security check fails
  254. * @see #getDeclaredConstructors()
  255. * @since 1.1
  256. */
  257. public native Constructor<T> getDeclaredConstructor(Class<?>... args)
  258. throws NoSuchMethodException;
  259. /**
  260. * Get all the declared member classes and interfaces in this class, but
  261. * not those inherited from superclasses. This returns an array of length
  262. * 0 if there are no member classes, including for primitive types. A
  263. * security check may be performed, with
  264. * <code>checkMemberAccess(this, Member.DECLARED)</code> as well as
  265. * <code>checkPackageAccess</code> both having to succeed.
  266. *
  267. * @return all declared member classes in this class
  268. * @throws SecurityException if the security check fails
  269. * @since 1.1
  270. */
  271. public Class<?>[] getDeclaredClasses()
  272. {
  273. memberAccessCheck(Member.DECLARED);
  274. return getDeclaredClasses(false);
  275. }
  276. native Class<?>[] getDeclaredClasses (boolean publicOnly);
  277. /**
  278. * Get all the declared constructors of this class. This returns an array of
  279. * length 0 if there are no constructors, including for primitive types,
  280. * arrays, and interfaces. It does, however, include the default
  281. * constructor if one was supplied by the compiler. A security check may
  282. * be performed, with <code>checkMemberAccess(this, Member.DECLARED)</code>
  283. * as well as <code>checkPackageAccess</code> both having to succeed.
  284. *
  285. * @return all constructors in this class
  286. * @throws SecurityException if the security check fails
  287. * @since 1.1
  288. */
  289. public Constructor<?>[] getDeclaredConstructors()
  290. {
  291. memberAccessCheck(Member.DECLARED);
  292. return getDeclaredConstructors(false);
  293. }
  294. native Constructor<?>[] getDeclaredConstructors (boolean publicOnly);
  295. /**
  296. * Get a field declared in this class, where name is its simple name. The
  297. * implicit length field of arrays is not available. A security check may
  298. * be performed, with <code>checkMemberAccess(this, Member.DECLARED)</code>
  299. * as well as <code>checkPackageAccess</code> both having to succeed.
  300. *
  301. * @param name the name of the field
  302. * @return the field
  303. * @throws NoSuchFieldException if the field does not exist
  304. * @throws SecurityException if the security check fails
  305. * @see #getDeclaredFields()
  306. * @since 1.1
  307. */
  308. public native Field getDeclaredField(String fieldName)
  309. throws NoSuchFieldException;
  310. /**
  311. * Get all the declared fields in this class, but not those inherited from
  312. * superclasses. This returns an array of length 0 if there are no fields,
  313. * including for primitive types. This does not return the implicit length
  314. * field of arrays. A security check may be performed, with
  315. * <code>checkMemberAccess(this, Member.DECLARED)</code> as well as
  316. * <code>checkPackageAccess</code> both having to succeed.
  317. *
  318. * @return all declared fields in this class
  319. * @throws SecurityException if the security check fails
  320. * @since 1.1
  321. */
  322. public Field[] getDeclaredFields()
  323. {
  324. memberAccessCheck(Member.DECLARED);
  325. return getDeclaredFields(false);
  326. }
  327. native Field[] getDeclaredFields (boolean publicOnly);
  328. private native Method _getDeclaredMethod(String methodName, Class[] args);
  329. /**
  330. * Get a method declared in this class, where name is its simple name. The
  331. * implicit methods of Object are not available from arrays or interfaces.
  332. * Constructors (named "&lt;init&gt;" in the class file) and class initializers
  333. * (name "&lt;clinit&gt;") are not available. The Virtual Machine allows
  334. * multiple methods with the same signature but differing return types; in
  335. * such a case the most specific return types are favored, then the final
  336. * choice is arbitrary. If the method takes no argument, an array of zero
  337. * elements and null are equivalent for the types argument. A security
  338. * check may be performed, with
  339. * <code>checkMemberAccess(this, Member.DECLARED)</code> as well as
  340. * <code>checkPackageAccess</code> both having to succeed.
  341. *
  342. * @param methodName the name of the method
  343. * @param types the type of each parameter
  344. * @return the method
  345. * @throws NoSuchMethodException if the method does not exist
  346. * @throws SecurityException if the security check fails
  347. * @see #getDeclaredMethods()
  348. * @since 1.1
  349. */
  350. public Method getDeclaredMethod(String methodName, Class<?>... args)
  351. throws NoSuchMethodException
  352. {
  353. memberAccessCheck(Member.DECLARED);
  354. if ("<init>".equals(methodName) || "<clinit>".equals(methodName))
  355. throw new NoSuchMethodException(methodName);
  356. Method match = _getDeclaredMethod(methodName, args);
  357. if (match == null)
  358. throw new NoSuchMethodException(methodName);
  359. return match;
  360. }
  361. /**
  362. * Get all the declared methods in this class, but not those inherited from
  363. * superclasses. This returns an array of length 0 if there are no methods,
  364. * including for primitive types. This does include the implicit methods of
  365. * arrays and interfaces which mirror methods of Object, nor does it
  366. * include constructors or the class initialization methods. The Virtual
  367. * Machine allows multiple methods with the same signature but differing
  368. * return types; all such methods are in the returned array. A security
  369. * check may be performed, with
  370. * <code>checkMemberAccess(this, Member.DECLARED)</code> as well as
  371. * <code>checkPackageAccess</code> both having to succeed.
  372. *
  373. * @return all declared methods in this class
  374. * @throws SecurityException if the security check fails
  375. * @since 1.1
  376. */
  377. public native Method[] getDeclaredMethods();
  378. /**
  379. * If this is a nested or inner class, return the class that declared it.
  380. * If not, return null.
  381. *
  382. * @return the declaring class of this class
  383. * @since 1.1
  384. */
  385. // This is marked as unimplemented in the JCL book.
  386. public native Class<?> getDeclaringClass ();
  387. private native Field getField (String fieldName, int hash)
  388. throws NoSuchFieldException;
  389. /**
  390. * Get a public field declared or inherited in this class, where name is
  391. * its simple name. If the class contains multiple accessible fields by
  392. * that name, an arbitrary one is returned. The implicit length field of
  393. * arrays is not available. A security check may be performed, with
  394. * <code>checkMemberAccess(this, Member.PUBLIC)</code> as well as
  395. * <code>checkPackageAccess</code> both having to succeed.
  396. *
  397. * @param fieldName the name of the field
  398. * @return the field
  399. * @throws NoSuchFieldException if the field does not exist
  400. * @throws SecurityException if the security check fails
  401. * @see #getFields()
  402. * @since 1.1
  403. */
  404. public Field getField(String fieldName)
  405. throws NoSuchFieldException
  406. {
  407. memberAccessCheck(Member.PUBLIC);
  408. Field field = getField(fieldName, fieldName.hashCode());
  409. if (field == null)
  410. throw new NoSuchFieldException(fieldName);
  411. return field;
  412. }
  413. /**
  414. * Get all the public fields declared in this class or inherited from
  415. * superclasses. This returns an array of length 0 if there are no fields,
  416. * including for primitive types. This does not return the implicit length
  417. * field of arrays. A security check may be performed, with
  418. * <code>checkMemberAccess(this, Member.PUBLIC)</code> as well as
  419. * <code>checkPackageAccess</code> both having to succeed.
  420. *
  421. * @return all public fields in this class
  422. * @throws SecurityException if the security check fails
  423. * @since 1.1
  424. */
  425. public Field[] getFields()
  426. {
  427. memberAccessCheck(Member.PUBLIC);
  428. return internalGetFields();
  429. }
  430. /**
  431. * Like <code>getFields()</code> but without the security checks.
  432. */
  433. private Field[] internalGetFields()
  434. {
  435. LinkedHashSet set = new LinkedHashSet();
  436. set.addAll(Arrays.asList(getDeclaredFields(true)));
  437. Class[] interfaces = getInterfaces();
  438. for (int i = 0; i < interfaces.length; i++)
  439. set.addAll(Arrays.asList(interfaces[i].internalGetFields()));
  440. Class superClass = getSuperclass();
  441. if (superClass != null)
  442. set.addAll(Arrays.asList(superClass.internalGetFields()));
  443. return (Field[])set.toArray(new Field[set.size()]);
  444. }
  445. /**
  446. * Returns the <code>Package</code> in which this class is defined
  447. * Returns null when this information is not available from the
  448. * classloader of this class.
  449. *
  450. * @return the package for this class, if it is available
  451. * @since 1.2
  452. */
  453. public Package getPackage()
  454. {
  455. ClassLoader cl = getClassLoaderInternal();
  456. if (cl != null)
  457. return cl.getPackage(getPackagePortion(getName()));
  458. else
  459. return VMClassLoader.getPackage(getPackagePortion(getName()));
  460. }
  461. /**
  462. * Get the interfaces this class <em>directly</em> implements, in the
  463. * order that they were declared. This returns an empty array, not null,
  464. * for Object, primitives, void, and classes or interfaces with no direct
  465. * superinterface. Array types return Cloneable and Serializable.
  466. *
  467. * @return the interfaces this class directly implements
  468. */
  469. public native Class<?>[] getInterfaces ();
  470. private final native void getSignature(StringBuffer buffer);
  471. private static final native String getSignature(Class[] args,
  472. boolean is_construtor);
  473. public native Method _getMethod(String methodName, Class[] args);
  474. /**
  475. * Get a public method declared or inherited in this class, where name is
  476. * its simple name. The implicit methods of Object are not available from
  477. * interfaces. Constructors (named "&lt;init&gt;" in the class file) and class
  478. * initializers (name "&lt;clinit&gt;") are not available. The Virtual
  479. * Machine allows multiple methods with the same signature but differing
  480. * return types, and the class can inherit multiple methods of the same
  481. * return type; in such a case the most specific return types are favored,
  482. * then the final choice is arbitrary. If the method takes no argument, an
  483. * array of zero elements and null are equivalent for the types argument.
  484. * A security check may be performed, with
  485. * <code>checkMemberAccess(this, Member.PUBLIC)</code> as well as
  486. * <code>checkPackageAccess</code> both having to succeed.
  487. *
  488. * @param methodName the name of the method
  489. * @param types the type of each parameter
  490. * @return the method
  491. * @throws NoSuchMethodException if the method does not exist
  492. * @throws SecurityException if the security check fails
  493. * @see #getMethods()
  494. * @since 1.1
  495. */
  496. public Method getMethod(String methodName, Class<?>... args)
  497. throws NoSuchMethodException
  498. {
  499. memberAccessCheck(Member.PUBLIC);
  500. if ("<init>".equals(methodName) || "<clinit>".equals(methodName))
  501. throw new NoSuchMethodException(methodName);
  502. Method method = _getMethod(methodName, args);
  503. if (method == null)
  504. throw new NoSuchMethodException(methodName);
  505. return method;
  506. }
  507. private native int _getMethods (Method[] result, int offset);
  508. /**
  509. * Get all the public methods declared in this class or inherited from
  510. * superclasses. This returns an array of length 0 if there are no methods,
  511. * including for primitive types. This does not include the implicit
  512. * methods of interfaces which mirror methods of Object, nor does it
  513. * include constructors or the class initialization methods. The Virtual
  514. * Machine allows multiple methods with the same signature but differing
  515. * return types; all such methods are in the returned array. A security
  516. * check may be performed, with
  517. * <code>checkMemberAccess(this, Member.PUBLIC)</code> as well as
  518. * <code>checkPackageAccess</code> both having to succeed.
  519. *
  520. * @return all public methods in this class
  521. * @throws SecurityException if the security check fails
  522. * @since 1.1
  523. */
  524. public native Method[] getMethods();
  525. /**
  526. * Get the modifiers of this class. These can be decoded using Modifier,
  527. * and is limited to one of public, protected, or private, and any of
  528. * final, static, abstract, or interface. An array class has the same
  529. * public, protected, or private modifier as its component type, and is
  530. * marked final but not an interface. Primitive types and void are marked
  531. * public and final, but not an interface.
  532. *
  533. * @return the modifiers of this class
  534. * @see Modifer
  535. * @since 1.1
  536. */
  537. public native int getModifiers ();
  538. /**
  539. * Get the name of this class, separated by dots for package separators.
  540. * If the class represents a primitive type, or void, then the
  541. * name of the type as it appears in the Java programming language
  542. * is returned. For instance, <code>Byte.TYPE.getName()</code>
  543. * returns "byte".
  544. *
  545. * Arrays are specially encoded as shown on this table.
  546. * <pre>
  547. * array type [<em>element type</em>
  548. * (note that the element type is encoded per
  549. * this table)
  550. * boolean Z
  551. * byte B
  552. * char C
  553. * short S
  554. * int I
  555. * long J
  556. * float F
  557. * double D
  558. * void V
  559. * class or interface, alone: &lt;dotted name&gt;
  560. * class or interface, as element type: L&lt;dotted name&gt;;
  561. * </pre>
  562. *
  563. * @return the name of this class
  564. */
  565. public native String getName ();
  566. /**
  567. * Get a resource URL using this class's package using the
  568. * getClassLoader().getResource() method. If this class was loaded using
  569. * the system classloader, ClassLoader.getSystemResource() is used instead.
  570. *
  571. * <p>If the name you supply is absolute (it starts with a <code>/</code>),
  572. * then the leading <code>/</code> is removed and it is passed on to
  573. * getResource(). If it is relative, the package name is prepended, and
  574. * <code>.</code>'s are replaced with <code>/</code>.
  575. *
  576. * <p>The URL returned is system- and classloader-dependent, and could
  577. * change across implementations.
  578. *
  579. * @param resourceName the name of the resource, generally a path
  580. * @return the URL to the resource
  581. * @throws NullPointerException if name is null
  582. * @since 1.1
  583. */
  584. public URL getResource(String resourceName)
  585. {
  586. String name = resourcePath(resourceName);
  587. ClassLoader loader = getClassLoaderInternal();
  588. if (loader == null)
  589. return ClassLoader.getSystemResource(name);
  590. return loader.getResource(name);
  591. }
  592. /**
  593. * Get a resource using this class's package using the
  594. * getClassLoader().getResourceAsStream() method. If this class was loaded
  595. * using the system classloader, ClassLoader.getSystemResource() is used
  596. * instead.
  597. *
  598. * <p>If the name you supply is absolute (it starts with a <code>/</code>),
  599. * then the leading <code>/</code> is removed and it is passed on to
  600. * getResource(). If it is relative, the package name is prepended, and
  601. * <code>.</code>'s are replaced with <code>/</code>.
  602. *
  603. * <p>The URL returned is system- and classloader-dependent, and could
  604. * change across implementations.
  605. *
  606. * @param resourceName the name of the resource, generally a path
  607. * @return an InputStream with the contents of the resource in it, or null
  608. * @throws NullPointerException if name is null
  609. * @since 1.1
  610. */
  611. public InputStream getResourceAsStream(String resourceName)
  612. {
  613. String name = resourcePath(resourceName);
  614. ClassLoader loader = getClassLoaderInternal();
  615. if (loader == null)
  616. return ClassLoader.getSystemResourceAsStream(name);
  617. return loader.getResourceAsStream(name);
  618. }
  619. private String resourcePath(String resourceName)
  620. {
  621. if (resourceName.length() > 0)
  622. {
  623. if (resourceName.charAt(0) != '/')
  624. {
  625. String pkg = getPackagePortion(getName());
  626. if (pkg.length() > 0)
  627. resourceName = pkg.replace('.','/') + '/' + resourceName;
  628. }
  629. else
  630. {
  631. resourceName = resourceName.substring(1);
  632. }
  633. }
  634. return resourceName;
  635. }
  636. /**
  637. * Get the signers of this class. This returns null if there are no signers,
  638. * such as for primitive types or void.
  639. *
  640. * @return the signers of this class
  641. * @since 1.1
  642. */
  643. public native Object[] getSigners ();
  644. /**
  645. * Set the signers of this class.
  646. *
  647. * @param signers the signers of this class
  648. */
  649. native void setSigners(Object[] signers);
  650. /**
  651. * Get the direct superclass of this class. If this is an interface,
  652. * Object, a primitive type, or void, it will return null. If this is an
  653. * array type, it will return Object.
  654. *
  655. * @return the direct superclass of this class
  656. */
  657. public native Class<? super T> getSuperclass ();
  658. /**
  659. * Return whether this class is an array type.
  660. *
  661. * @return whether this class is an array type
  662. * @since 1.1
  663. */
  664. public native boolean isArray ();
  665. /**
  666. * Discover whether an instance of the Class parameter would be an
  667. * instance of this Class as well. Think of doing
  668. * <code>isInstance(c.newInstance())</code> or even
  669. * <code>c.newInstance() instanceof (this class)</code>. While this
  670. * checks widening conversions for objects, it must be exact for primitive
  671. * types.
  672. *
  673. * @param c the class to check
  674. * @return whether an instance of c would be an instance of this class
  675. * as well
  676. * @throws NullPointerException if c is null
  677. * @since 1.1
  678. */
  679. public native boolean isAssignableFrom (Class<?> c);
  680. /**
  681. * Discover whether an Object is an instance of this Class. Think of it
  682. * as almost like <code>o instanceof (this class)</code>.
  683. *
  684. * @param o the Object to check
  685. * @return whether o is an instance of this class
  686. * @since 1.1
  687. */
  688. public native boolean isInstance (Object o);
  689. /**
  690. * Check whether this class is an interface or not. Array types are not
  691. * interfaces.
  692. *
  693. * @return whether this class is an interface or not
  694. */
  695. public native boolean isInterface ();
  696. /**
  697. * Return whether this class is a primitive type. A primitive type class
  698. * is a class representing a kind of "placeholder" for the various
  699. * primitive types, or void. You can access the various primitive type
  700. * classes through java.lang.Boolean.TYPE, java.lang.Integer.TYPE, etc.,
  701. * or through boolean.class, int.class, etc.
  702. *
  703. * @return whether this class is a primitive type
  704. * @see Boolean#TYPE
  705. * @see Byte#TYPE
  706. * @see Character#TYPE
  707. * @see Short#TYPE
  708. * @see Integer#TYPE
  709. * @see Long#TYPE
  710. * @see Float#TYPE
  711. * @see Double#TYPE
  712. * @see Void#TYPE
  713. * @since 1.1
  714. */
  715. public native boolean isPrimitive ();
  716. /**
  717. * Get a new instance of this class by calling the no-argument constructor.
  718. * The class is initialized if it has not been already. A security check
  719. * may be performed, with <code>checkMemberAccess(this, Member.PUBLIC)</code>
  720. * as well as <code>checkPackageAccess</code> both having to succeed.
  721. *
  722. * @return a new instance of this class
  723. * @throws InstantiationException if there is not a no-arg constructor
  724. * for this class, including interfaces, abstract classes, arrays,
  725. * primitive types, and void; or if an exception occurred during
  726. * the constructor
  727. * @throws IllegalAccessException if you are not allowed to access the
  728. * no-arg constructor because of scoping reasons
  729. * @throws SecurityException if the security check fails
  730. * @throws ExceptionInInitializerError if class initialization caused by
  731. * this call fails with an exception
  732. */
  733. public native T newInstance ()
  734. throws InstantiationException, IllegalAccessException;
  735. // We need a native method to retrieve the protection domain, because we
  736. // can't add fields to java.lang.Class that are accessible from Java.
  737. private native ProtectionDomain getProtectionDomain0();
  738. /**
  739. * Returns the protection domain of this class. If the classloader did not
  740. * record the protection domain when creating this class the unknown
  741. * protection domain is returned which has a <code>null</code> code source
  742. * and all permissions. A security check may be performed, with
  743. * <code>RuntimePermission("getProtectionDomain")</code>.
  744. *
  745. * @return the protection domain
  746. * @throws SecurityException if the security manager exists and the caller
  747. * does not have <code>RuntimePermission("getProtectionDomain")</code>.
  748. * @see RuntimePermission
  749. * @since 1.2
  750. */
  751. public ProtectionDomain getProtectionDomain()
  752. {
  753. SecurityManager sm = System.getSecurityManager();
  754. if (sm != null)
  755. sm.checkPermission(VMClassLoader.protectionDomainPermission);
  756. ProtectionDomain protectionDomain = getProtectionDomain0();
  757. if (protectionDomain == null)
  758. return VMClassLoader.unknownProtectionDomain;
  759. else
  760. return protectionDomain;
  761. }
  762. /**
  763. * Return the human-readable form of this Object. For an object, this
  764. * is either "interface " or "class " followed by <code>getName()</code>,
  765. * for primitive types and void it is just <code>getName()</code>.
  766. *
  767. * @return the human-readable form of this Object
  768. */
  769. public String toString()
  770. {
  771. if (isPrimitive())
  772. return getName();
  773. return (isInterface() ? "interface " : "class ") + getName();
  774. }
  775. /**
  776. * Returns the desired assertion status of this class, if it were to be
  777. * initialized at this moment. The class assertion status, if set, is
  778. * returned; the backup is the default package status; then if there is
  779. * a class loader, that default is returned; and finally the system default
  780. * is returned. This method seldom needs calling in user code, but exists
  781. * for compilers to implement the assert statement. Note that there is no
  782. * guarantee that the result of this method matches the class's actual
  783. * assertion status.
  784. *
  785. * @return the desired assertion status
  786. * @see ClassLoader#setClassAssertionStatus(String, boolean)
  787. * @see ClassLoader#setPackageAssertionStatus(String, boolean)
  788. * @see ClassLoader#setDefaultAssertionStatus(boolean)
  789. * @since 1.4
  790. */
  791. public boolean desiredAssertionStatus()
  792. {
  793. ClassLoader c = getClassLoaderInternal();
  794. Object status;
  795. if (c == null)
  796. return VMClassLoader.defaultAssertionStatus();
  797. if (c.classAssertionStatus != null)
  798. synchronized (c)
  799. {
  800. status = c.classAssertionStatus.get(getName());
  801. if (status != null)
  802. return status.equals(Boolean.TRUE);
  803. }
  804. else
  805. {
  806. status = ClassLoader.systemClassAssertionStatus.get(getName());
  807. if (status != null)
  808. return status.equals(Boolean.TRUE);
  809. }
  810. if (c.packageAssertionStatus != null)
  811. synchronized (c)
  812. {
  813. String name = getPackagePortion(getName());
  814. if ("".equals(name))
  815. status = c.packageAssertionStatus.get(null);
  816. else
  817. do
  818. {
  819. status = c.packageAssertionStatus.get(name);
  820. name = getPackagePortion(name);
  821. }
  822. while (! "".equals(name) && status == null);
  823. if (status != null)
  824. return status.equals(Boolean.TRUE);
  825. }
  826. else
  827. {
  828. String name = getPackagePortion(getName());
  829. if ("".equals(name))
  830. status = ClassLoader.systemPackageAssertionStatus.get(null);
  831. else
  832. do
  833. {
  834. status = ClassLoader.systemPackageAssertionStatus.get(name);
  835. name = getPackagePortion(name);
  836. }
  837. while (! "".equals(name) && status == null);
  838. if (status != null)
  839. return status.equals(Boolean.TRUE);
  840. }
  841. return c.defaultAssertionStatus;
  842. }
  843. /**
  844. * Strip the last portion of the name (after the last dot).
  845. *
  846. * @param name the name to get package of
  847. * @return the package name, or "" if no package
  848. */
  849. private static String getPackagePortion(String name)
  850. {
  851. int lastInd = name.lastIndexOf('.');
  852. if (lastInd == -1)
  853. return "";
  854. return name.substring(0, lastInd);
  855. }
  856. /**
  857. * Perform security checks common to all of the methods that
  858. * get members of this Class.
  859. */
  860. private void memberAccessCheck(int which)
  861. {
  862. SecurityManager sm = System.getSecurityManager();
  863. if (sm != null)
  864. {
  865. sm.checkMemberAccess(this, which);
  866. Package pkg = getPackage();
  867. if (pkg != null)
  868. sm.checkPackageAccess(pkg.getName());
  869. }
  870. }
  871. /**
  872. * <p>
  873. * Casts this class to represent a subclass of the specified class.
  874. * This method is useful for `narrowing' the type of a class so that
  875. * the class object, and instances of that class, can match the contract
  876. * of a more restrictive method. For example, if this class has the
  877. * static type of <code>Class&lt;Object&gt;</code>, and a dynamic type of
  878. * <code>Class&lt;Rectangle&gt;</code>, then, assuming <code>Shape</code> is
  879. * a superclass of <code>Rectangle</code>, this method can be used on
  880. * this class with the parameter, <code>Class&lt;Shape&gt;</code>, to retain
  881. * the same instance but with the type
  882. * <code>Class&lt;? extends Shape&gt;</code>.
  883. * </p>
  884. * <p>
  885. * If this class can be converted to an instance which is parameterised
  886. * over a subtype of the supplied type, <code>U</code>, then this method
  887. * returns an appropriately cast reference to this object. Otherwise,
  888. * a <code>ClassCastException</code> is thrown.
  889. * </p>
  890. *
  891. * @param klass the class object, the parameterized type (<code>U</code>) of
  892. * which should be a superclass of the parameterized type of
  893. * this instance.
  894. * @return a reference to this object, appropriately cast.
  895. * @throws ClassCastException if this class can not be converted to one
  896. * which represents a subclass of the specified
  897. * type, <code>U</code>.
  898. * @since 1.5
  899. */
  900. public <U> Class<? extends U> asSubclass(Class<U> klass)
  901. {
  902. if (! klass.isAssignableFrom(this))
  903. throw new ClassCastException();
  904. return (Class<? extends U>) this;
  905. }
  906. /**
  907. * Returns the specified object, cast to this <code>Class</code>' type.
  908. *
  909. * @param obj the object to cast
  910. * @throws ClassCastException if obj is not an instance of this class
  911. * @since 1.5
  912. */
  913. public T cast(Object obj)
  914. {
  915. if (obj != null && ! isInstance(obj))
  916. throw new ClassCastException();
  917. return (T) obj;
  918. }
  919. /**
  920. * Returns the enumeration constants of this class, or
  921. * null if this class is not an <code>Enum</code>.
  922. *
  923. * @return an array of <code>Enum</code> constants
  924. * associated with this class, or null if this
  925. * class is not an <code>enum</code>.
  926. * @since 1.5
  927. */
  928. public T[] getEnumConstants()
  929. {
  930. if (isEnum())
  931. {
  932. try
  933. {
  934. Method m = getMethod("values");
  935. setAccessible(m);
  936. return (T[]) m.invoke(null);
  937. }
  938. catch (NoSuchMethodException exception)
  939. {
  940. throw new Error("Enum lacks values() method");
  941. }
  942. catch (IllegalAccessException exception)
  943. {
  944. throw new Error("Unable to access Enum class");
  945. }
  946. catch (InvocationTargetException exception)
  947. {
  948. throw new
  949. RuntimeException("The values method threw an exception",
  950. exception);
  951. }
  952. }
  953. else
  954. {
  955. return null;
  956. }
  957. }
  958. /**
  959. * Returns true if this class is an <code>Enum</code>.
  960. *
  961. * @return true if this is an enumeration class.
  962. * @since 1.5
  963. */
  964. public native boolean isEnum();
  965. /**
  966. * Returns true if this class is a synthetic class, generated by
  967. * the compiler.
  968. *
  969. * @return true if this is a synthetic class.
  970. * @since 1.5
  971. */
  972. public native boolean isSynthetic();
  973. /**
  974. * Returns true if this class is an <code>Annotation</code>.
  975. *
  976. * @return true if this is an annotation class.
  977. * @since 1.5
  978. */
  979. public native boolean isAnnotation();
  980. /**
  981. * Returns the simple name for this class, as used in the source
  982. * code. For normal classes, this is the content returned by
  983. * <code>getName()</code> which follows the last ".". Anonymous
  984. * classes have no name, and so the result of calling this method is
  985. * "". The simple name of an array consists of the simple name of
  986. * its component type, followed by "[]". Thus, an array with the
  987. * component type of an anonymous class has a simple name of simply
  988. * "[]".
  989. *
  990. * @return the simple name for this class.
  991. * @since 1.5
  992. */
  993. public String getSimpleName()
  994. {
  995. if (isAnonymousClass())
  996. return "";
  997. if (isArray())
  998. return getComponentType().getSimpleName() + "[]";
  999. String fullName = getName();
  1000. Class enclosingClass = getEnclosingClass();
  1001. if (enclosingClass == null)
  1002. // It's a top level class.
  1003. return fullName.substring(fullName.lastIndexOf(".") + 1);
  1004. fullName = fullName.substring(enclosingClass.getName().length());
  1005. // We've carved off the enclosing class name; now we must have '$'
  1006. // followed optionally by digits, followed by the class name.
  1007. int pos = 1;
  1008. while (Character.isDigit(fullName.charAt(pos)))
  1009. ++pos;
  1010. fullName = fullName.substring(pos);
  1011. return fullName;
  1012. }
  1013. /**
  1014. * Returns the class which immediately encloses this class. If this class
  1015. * is a top-level class, this method returns <code>null</code>.
  1016. *
  1017. * @return the immediate enclosing class, or <code>null</code> if this is
  1018. * a top-level class.
  1019. * @since 1.5
  1020. */
  1021. public native Class<?> getEnclosingClass();
  1022. /**
  1023. * Returns the constructor which immediately encloses this class. If
  1024. * this class is a top-level class, or a local or anonymous class
  1025. * immediately enclosed by a type definition, instance initializer
  1026. * or static initializer, then <code>null</code> is returned.
  1027. *
  1028. * @return the immediate enclosing constructor if this class is
  1029. * declared within a constructor. Otherwise, <code>null</code>
  1030. * is returned.
  1031. * @since 1.5
  1032. */
  1033. public native Constructor<T> getEnclosingConstructor();
  1034. /**
  1035. * Returns the method which immediately encloses this class. If
  1036. * this class is a top-level class, or a local or anonymous class
  1037. * immediately enclosed by a type definition, instance initializer
  1038. * or static initializer, then <code>null</code> is returned.
  1039. *
  1040. * @return the immediate enclosing method if this class is
  1041. * declared within a method. Otherwise, <code>null</code>
  1042. * is returned.
  1043. * @since 1.5
  1044. */
  1045. public native Method getEnclosingMethod();
  1046. private native String getClassSignature();
  1047. /**
  1048. * <p>
  1049. * Returns an array of <code>Type</code> objects which represent the
  1050. * interfaces directly implemented by this class or extended by this
  1051. * interface.
  1052. * </p>
  1053. * <p>
  1054. * If one of the superinterfaces is a parameterized type, then the
  1055. * object returned for this interface reflects the actual type
  1056. * parameters used in the source code. Type parameters are created
  1057. * using the semantics specified by the <code>ParameterizedType</code>
  1058. * interface, and only if an instance has not already been created.
  1059. * </p>
  1060. * <p>
  1061. * The order of the interfaces in the array matches the order in which
  1062. * the interfaces are declared. For classes which represent an array,
  1063. * an array of two interfaces, <code>Cloneable</code> and
  1064. * <code>Serializable</code>, is always returned, with the objects in
  1065. * that order. A class representing a primitive type or void always
  1066. * returns an array of zero size.
  1067. * </p>
  1068. *
  1069. * @return an array of interfaces implemented or extended by this class.
  1070. * @throws GenericSignatureFormatError if the generic signature of one
  1071. * of the interfaces does not comply with that specified by the Java
  1072. * Virtual Machine specification, 3rd edition.
  1073. * @throws TypeNotPresentException if any of the superinterfaces refers
  1074. * to a non-existant type.
  1075. * @throws MalformedParameterizedTypeException if any of the interfaces
  1076. * refer to a parameterized type that can not be instantiated for
  1077. * some reason.
  1078. * @since 1.5
  1079. * @see java.lang.reflect.ParameterizedType
  1080. */
  1081. public Type[] getGenericInterfaces()
  1082. {
  1083. if (isPrimitive())
  1084. return new Type[0];
  1085. String sig = getClassSignature();
  1086. if (sig == null)
  1087. return getInterfaces();
  1088. ClassSignatureParser p = new ClassSignatureParser(this, sig);
  1089. return p.getInterfaceTypes();
  1090. }
  1091. /**
  1092. * <p>
  1093. * Returns a <code>Type</code> object representing the direct superclass,
  1094. * whether class, interface, primitive type or void, of this class.
  1095. * If this class is an array class, then a class instance representing
  1096. * the <code>Object</code> class is returned. If this class is primitive,
  1097. * an interface, or a representation of either the <code>Object</code>
  1098. * class or void, then <code>null</code> is returned.
  1099. * </p>
  1100. * <p>
  1101. * If the superclass is a parameterized type, then the
  1102. * object returned for this interface reflects the actual type
  1103. * parameters used in the source code. Type parameters are created
  1104. * using the semantics specified by the <code>ParameterizedType</code>
  1105. * interface, and only if an instance has not already been created.
  1106. * </p>
  1107. *
  1108. * @return the superclass of this class.
  1109. * @throws GenericSignatureFormatError if the generic signature of the
  1110. * class does not comply with that specified by the Java
  1111. * Virtual Machine specification, 3rd edition.
  1112. * @throws TypeNotPresentException if the superclass refers
  1113. * to a non-existant type.
  1114. * @throws MalformedParameterizedTypeException if the superclass
  1115. * refers to a parameterized type that can not be instantiated for
  1116. * some reason.
  1117. * @since 1.5
  1118. * @see java.lang.reflect.ParameterizedType
  1119. */
  1120. public Type getGenericSuperclass()
  1121. {
  1122. if (isArray())
  1123. return Object.class;
  1124. if (isPrimitive() || isInterface() || this == Object.class)
  1125. return null;
  1126. String sig = getClassSignature();
  1127. if (sig == null)
  1128. return getSuperclass();
  1129. ClassSignatureParser p = new ClassSignatureParser(this, sig);
  1130. return p.getSuperclassType();
  1131. }
  1132. /**
  1133. * Returns an array of <code>TypeVariable</code> objects that represents
  1134. * the type variables declared by this class, in declaration order.
  1135. * An array of size zero is returned if this class has no type
  1136. * variables.
  1137. *
  1138. * @return the type variables associated with this class.
  1139. * @throws GenericSignatureFormatError if the generic signature does
  1140. * not conform to the format specified in the Virtual Machine
  1141. * specification, version 3.
  1142. * @since 1.5
  1143. */
  1144. public TypeVariable<Class<T>>[] getTypeParameters()
  1145. {
  1146. String sig = getClassSignature();
  1147. if (sig == null)
  1148. return (TypeVariable<Class<T>>[])new TypeVariable[0];
  1149. ClassSignatureParser p = new ClassSignatureParser(this, sig);
  1150. return p.getTypeParameters();
  1151. }
  1152. /**
  1153. * Returns this class' annotation for the specified annotation type,
  1154. * or <code>null</code> if no such annotation exists.
  1155. *
  1156. * @param annotationClass the type of annotation to look for.
  1157. * @return this class' annotation for the specified type, or
  1158. * <code>null</code> if no such annotation exists.
  1159. * @since 1.5
  1160. */
  1161. public <A extends Annotation> A getAnnotation(Class<A> annotationClass)
  1162. {
  1163. A foundAnnotation = null;
  1164. Annotation[] annotations = getAnnotations();
  1165. for (Annotation annotation : annotations)
  1166. if (annotation.annotationType() == annotationClass)
  1167. foundAnnotation = (A) annotation;
  1168. return foundAnnotation;
  1169. }
  1170. /**
  1171. * Returns all annotations associated with this class. If there are
  1172. * no annotations associated with this class, then a zero-length array
  1173. * will be returned. The returned array may be modified by the client
  1174. * code, but this will have no effect on the annotation content of this
  1175. * class, and hence no effect on the return value of this method for
  1176. * future callers.
  1177. *
  1178. * @return this class' annotations.
  1179. * @since 1.5
  1180. */
  1181. public Annotation[] getAnnotations()
  1182. {
  1183. HashMap<Class, Annotation> map = new HashMap<Class, Annotation>();
  1184. for (Annotation a : getDeclaredAnnotations())
  1185. map.put((Class) a.annotationType(), a);
  1186. for (Class<? super T> s = getSuperclass();
  1187. s != null;
  1188. s = s.getSuperclass())
  1189. {
  1190. for (Annotation a : s.getDeclaredAnnotations())
  1191. {
  1192. Class k = (Class) a.annotationType();
  1193. if (! map.containsKey(k) && k.isAnnotationPresent(Inherited.class))
  1194. map.put(k, a);
  1195. }
  1196. }
  1197. Collection<Annotation> v = map.values();
  1198. return v.toArray(new Annotation[v.size()]);
  1199. }
  1200. /**
  1201. * <p>
  1202. * Returns the canonical name of this class, as defined by section
  1203. * 6.7 of the Java language specification. Each package, top-level class,
  1204. * top-level interface and primitive type has a canonical name. A member
  1205. * class has a canonical name, if its parent class has one. Likewise,
  1206. * an array type has a canonical name, if its component type does.
  1207. * Local or anonymous classes do not have canonical names.
  1208. * </p>
  1209. * <p>
  1210. * The canonical name for top-level classes, top-level interfaces and
  1211. * primitive types is always the same as the fully-qualified name.
  1212. * For array types, the canonical name is the canonical name of its
  1213. * component type with `[]' appended.
  1214. * </p>
  1215. * <p>
  1216. * The canonical name of a member class always refers to the place where
  1217. * the class was defined, and is composed of the canonical name of the
  1218. * defining class and the simple name of the member class, joined by `.'.
  1219. * For example, if a <code>Person</code> class has an inner class,
  1220. * <code>M</code>, then both its fully-qualified name and canonical name
  1221. * is <code>Person.M</code>. A subclass, <code>Staff</code>, of
  1222. * <code>Person</code> refers to the same inner class by the fully-qualified
  1223. * name of <code>Staff.M</code>, but its canonical name is still
  1224. * <code>Person.M</code>.
  1225. * </p>
  1226. * <p>
  1227. * Where no canonical name is present, <code>null</code> is returned.
  1228. * </p>
  1229. *
  1230. * @return the canonical name of the class, or <code>null</code> if the
  1231. * class doesn't have a canonical name.
  1232. * @since 1.5
  1233. */
  1234. public String getCanonicalName()
  1235. {
  1236. if (isArray())
  1237. {
  1238. String componentName = getComponentType().getCanonicalName();
  1239. if (componentName != null)
  1240. return componentName + "[]";
  1241. }
  1242. if (isMemberClass())
  1243. {
  1244. String memberName = getDeclaringClass().getCanonicalName();
  1245. if (memberName != null)
  1246. return memberName + "." + getSimpleName();
  1247. }
  1248. if (isLocalClass() || isAnonymousClass())
  1249. return null;
  1250. return getName();
  1251. }
  1252. /**
  1253. * Returns all annotations directly defined by this class. If there are
  1254. * no annotations associated with this class, then a zero-length array
  1255. * will be returned. The returned array may be modified by the client
  1256. * code, but this will have no effect on the annotation content of this
  1257. * class, and hence no effect on the return value of this method for
  1258. * future callers.
  1259. *
  1260. * @return the annotations directly defined by this class.
  1261. * @since 1.5
  1262. */
  1263. public Annotation[] getDeclaredAnnotations()
  1264. {
  1265. Annotation[] result = getDeclaredAnnotationsInternal();
  1266. if (result == null)
  1267. result = new Annotation[0];
  1268. return result;
  1269. }
  1270. private native Annotation[] getDeclaredAnnotationsInternal();
  1271. /**
  1272. * Returns true if an annotation for the specified type is associated
  1273. * with this class. This is primarily a short-hand for using marker
  1274. * annotations.
  1275. *
  1276. * @param annotationClass the type of annotation to look for.
  1277. * @return true if an annotation exists for the specified type.
  1278. * @since 1.5
  1279. */
  1280. public boolean isAnnotationPresent(Class<? extends Annotation>
  1281. annotationClass)
  1282. {
  1283. return getAnnotation(annotationClass) != null;
  1284. }
  1285. /**
  1286. * Returns true if this object represents an anonymous class.
  1287. *
  1288. * @return true if this object represents an anonymous class.
  1289. * @since 1.5
  1290. */
  1291. public native boolean isAnonymousClass();
  1292. /**
  1293. * Returns true if this object represents an local class.
  1294. *
  1295. * @return true if this object represents an local class.
  1296. * @since 1.5
  1297. */
  1298. public native boolean isLocalClass();
  1299. /**
  1300. * Returns true if this object represents an member class.
  1301. *
  1302. * @return true if this object represents an member class.
  1303. * @since 1.5
  1304. */
  1305. public native boolean isMemberClass();
  1306. /**
  1307. * Utility method for use by classes in this package.
  1308. */
  1309. static void setAccessible(final AccessibleObject obj)
  1310. {
  1311. AccessController.doPrivileged(new PrivilegedAction()
  1312. {
  1313. public Object run()
  1314. {
  1315. obj.setAccessible(true);
  1316. return null;
  1317. }
  1318. });
  1319. }
  1320. }