Class.java 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812
  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.classpath.VMStackWalker;
  34. import gnu.java.lang.reflect.ClassSignatureParser;
  35. import java.io.InputStream;
  36. import java.io.Serializable;
  37. import java.lang.annotation.Annotation;
  38. import java.lang.annotation.Inherited;
  39. import java.lang.reflect.AccessibleObject;
  40. import java.lang.reflect.AnnotatedElement;
  41. import java.lang.reflect.Constructor;
  42. import java.lang.reflect.Field;
  43. import java.lang.reflect.GenericDeclaration;
  44. import java.lang.reflect.InvocationTargetException;
  45. import java.lang.reflect.Member;
  46. import java.lang.reflect.Method;
  47. import java.lang.reflect.Modifier;
  48. import java.lang.reflect.Type;
  49. import java.lang.reflect.TypeVariable;
  50. import java.net.URL;
  51. import java.security.AccessController;
  52. import java.security.AllPermission;
  53. import java.security.Permissions;
  54. import java.security.PrivilegedAction;
  55. import java.security.ProtectionDomain;
  56. import java.util.ArrayList;
  57. import java.util.Arrays;
  58. import java.util.Collection;
  59. import java.util.HashMap;
  60. import java.util.LinkedHashSet;
  61. /**
  62. * A Class represents a Java type. There will never be multiple Class
  63. * objects with identical names and ClassLoaders. Primitive types, array
  64. * types, and void also have a Class object.
  65. *
  66. * <p>Arrays with identical type and number of dimensions share the same class.
  67. * The array class ClassLoader is the same as the ClassLoader of the element
  68. * type of the array (which can be null to indicate the bootstrap classloader).
  69. * The name of an array class is <code>[&lt;signature format&gt;;</code>.
  70. * <p> For example,
  71. * String[]'s class is <code>[Ljava.lang.String;</code>. boolean, byte,
  72. * short, char, int, long, float and double have the "type name" of
  73. * Z,B,S,C,I,J,F,D for the purposes of array classes. If it's a
  74. * multidimensioned array, the same principle applies:
  75. * <code>int[][][]</code> == <code>[[[I</code>.
  76. *
  77. * <p>There is no public constructor - Class objects are obtained only through
  78. * the virtual machine, as defined in ClassLoaders.
  79. *
  80. * @serialData Class objects serialize specially:
  81. * <code>TC_CLASS ClassDescriptor</code>. For more serialization information,
  82. * see {@link ObjectStreamClass}.
  83. *
  84. * @author John Keiser
  85. * @author Eric Blake (ebb9@email.byu.edu)
  86. * @author Tom Tromey (tromey@redhat.com)
  87. * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
  88. * @since 1.0
  89. * @see ClassLoader
  90. */
  91. public final class Class<T>
  92. implements Serializable, Type, AnnotatedElement, GenericDeclaration
  93. {
  94. /**
  95. * Compatible with JDK 1.0+.
  96. */
  97. private static final long serialVersionUID = 3206093459760846163L;
  98. /**
  99. * Flag indicating a synthetic member.
  100. * Note that this duplicates a constant in Modifier.
  101. */
  102. private static final int SYNTHETIC = 0x1000;
  103. /**
  104. * Flag indiciating an annotation class.
  105. */
  106. private static final int ANNOTATION = 0x2000;
  107. /**
  108. * Flag indicating an enum constant or an enum class.
  109. * Note that this duplicates a constant in Modifier.
  110. */
  111. private static final int ENUM = 0x4000;
  112. /** The class signers. */
  113. private Object[] signers = null;
  114. /** The class protection domain. */
  115. private final transient ProtectionDomain pd;
  116. /* We use an inner class, so that Class doesn't have a static initializer */
  117. private static final class StaticData
  118. {
  119. static final ProtectionDomain unknownProtectionDomain;
  120. static
  121. {
  122. Permissions permissions = new Permissions();
  123. permissions.add(new AllPermission());
  124. unknownProtectionDomain = new ProtectionDomain(null, permissions);
  125. }
  126. }
  127. final transient Object vmdata;
  128. /** newInstance() caches the default constructor */
  129. private transient Constructor<T> constructor;
  130. /**
  131. * Class is non-instantiable from Java code; only the VM can create
  132. * instances of this class.
  133. */
  134. Class(Object vmdata)
  135. {
  136. this(vmdata, null);
  137. }
  138. Class(Object vmdata, ProtectionDomain pd)
  139. {
  140. this.vmdata = vmdata;
  141. // If the VM didn't supply a protection domain and the class is an array,
  142. // we "inherit" the protection domain from the component type class. This
  143. // saves the VM from having to worry about protection domains for array
  144. // classes.
  145. if (pd == null && isArray())
  146. this.pd = getComponentType().pd;
  147. else
  148. this.pd = pd;
  149. }
  150. /**
  151. * Use the classloader of the current class to load, link, and initialize
  152. * a class. This is equivalent to your code calling
  153. * <code>Class.forName(name, true, getClass().getClassLoader())</code>.
  154. *
  155. * @param name the name of the class to find
  156. * @return the Class object representing the class
  157. * @throws ClassNotFoundException if the class was not found by the
  158. * classloader
  159. * @throws LinkageError if linking the class fails
  160. * @throws ExceptionInInitializerError if the class loads, but an exception
  161. * occurs during initialization
  162. */
  163. public static Class<?> forName(String name) throws ClassNotFoundException
  164. {
  165. return VMClass.forName(name, true, VMStackWalker.getCallingClassLoader());
  166. }
  167. /**
  168. * Use the specified classloader to load and link a class. If the loader
  169. * is null, this uses the bootstrap class loader (provide the security
  170. * check succeeds). Unfortunately, this method cannot be used to obtain
  171. * the Class objects for primitive types or for void, you have to use
  172. * the fields in the appropriate java.lang wrapper classes.
  173. *
  174. * <p>Calls <code>classloader.loadclass(name, initialize)</code>.
  175. *
  176. * @param name the name of the class to find
  177. * @param initialize whether or not to initialize the class at this time
  178. * @param classloader the classloader to use to find the class; null means
  179. * to use the bootstrap class loader
  180. *
  181. * @return the class object for the given class
  182. *
  183. * @throws ClassNotFoundException if the class was not found by the
  184. * classloader
  185. * @throws LinkageError if linking the class fails
  186. * @throws ExceptionInInitializerError if the class loads, but an exception
  187. * occurs during initialization
  188. * @throws SecurityException if the <code>classloader</code> argument
  189. * is <code>null</code> and the caller does not have the
  190. * <code>RuntimePermission("getClassLoader")</code> permission
  191. * @see ClassLoader
  192. * @since 1.2
  193. */
  194. public static Class<?> forName(String name, boolean initialize,
  195. ClassLoader classloader)
  196. throws ClassNotFoundException
  197. {
  198. if (classloader == null)
  199. {
  200. // Check if we may access the bootstrap classloader
  201. SecurityManager sm = SecurityManager.current;
  202. if (sm != null)
  203. {
  204. // Get the calling classloader
  205. ClassLoader cl = VMStackWalker.getCallingClassLoader();
  206. if (cl != null)
  207. sm.checkPermission(new RuntimePermission("getClassLoader"));
  208. }
  209. }
  210. return (Class<?>) VMClass.forName(name, initialize, classloader);
  211. }
  212. /**
  213. * Get all the public member classes and interfaces declared in this
  214. * class or inherited from superclasses. This returns an array of length
  215. * 0 if there are no member classes, including for primitive types. A
  216. * security check may be performed, with
  217. * <code>checkMemberAccess(this, Member.PUBLIC)</code> as well as
  218. * <code>checkPackageAccess</code> both having to succeed.
  219. *
  220. * @return all public member classes in this class
  221. * @throws SecurityException if the security check fails
  222. * @since 1.1
  223. */
  224. public Class<?>[] getClasses()
  225. {
  226. memberAccessCheck(Member.PUBLIC);
  227. return internalGetClasses();
  228. }
  229. /**
  230. * Like <code>getClasses()</code> but without the security checks.
  231. */
  232. private Class<?>[] internalGetClasses()
  233. {
  234. ArrayList<Class> list = new ArrayList<Class>();
  235. list.addAll(Arrays.asList(getDeclaredClasses(true)));
  236. Class superClass = getSuperclass();
  237. if (superClass != null)
  238. list.addAll(Arrays.asList(superClass.internalGetClasses()));
  239. return list.toArray(new Class<?>[list.size()]);
  240. }
  241. /**
  242. * Get the ClassLoader that loaded this class. If the class was loaded
  243. * by the bootstrap classloader, this method will return null.
  244. * If there is a security manager, and the caller's class loader is not
  245. * an ancestor of the requested one, a security check of
  246. * <code>RuntimePermission("getClassLoader")</code>
  247. * must first succeed. Primitive types and void return null.
  248. *
  249. * @return the ClassLoader that loaded this class
  250. * @throws SecurityException if the security check fails
  251. * @see ClassLoader
  252. * @see RuntimePermission
  253. */
  254. public ClassLoader getClassLoader()
  255. {
  256. if (isPrimitive())
  257. return null;
  258. ClassLoader loader = VMClass.getClassLoader(this);
  259. // Check if we may get the classloader
  260. SecurityManager sm = SecurityManager.current;
  261. if (loader != null && sm != null)
  262. {
  263. // Get the calling classloader
  264. ClassLoader cl = VMStackWalker.getCallingClassLoader();
  265. if (cl != null && !cl.isAncestorOf(loader))
  266. sm.checkPermission(new RuntimePermission("getClassLoader"));
  267. }
  268. return loader;
  269. }
  270. /**
  271. * If this is an array, get the Class representing the type of array.
  272. * Examples: "[[Ljava.lang.String;" would return "[Ljava.lang.String;", and
  273. * calling getComponentType on that would give "java.lang.String". If
  274. * this is not an array, returns null.
  275. *
  276. * @return the array type of this class, or null
  277. * @see Array
  278. * @since 1.1
  279. */
  280. public Class<?> getComponentType()
  281. {
  282. return VMClass.getComponentType (this);
  283. }
  284. /**
  285. * Get a public constructor declared in this class. If the constructor takes
  286. * no argument, an array of zero elements and null are equivalent for the
  287. * types argument. A security check may be performed, with
  288. * <code>checkMemberAccess(this, Member.PUBLIC)</code> as well as
  289. * <code>checkPackageAccess</code> both having to succeed.
  290. *
  291. * @param types the type of each parameter
  292. * @return the constructor
  293. * @throws NoSuchMethodException if the constructor does not exist
  294. * @throws SecurityException if the security check fails
  295. * @see #getConstructors()
  296. * @since 1.1
  297. */
  298. public Constructor<T> getConstructor(Class<?>... types)
  299. throws NoSuchMethodException
  300. {
  301. memberAccessCheck(Member.PUBLIC);
  302. Constructor[] constructors = getDeclaredConstructors(true);
  303. for (int i = 0; i < constructors.length; i++)
  304. {
  305. Constructor constructor = constructors[i];
  306. if (matchParameters(types, constructor.getParameterTypes()))
  307. return constructor;
  308. }
  309. throw new NoSuchMethodException();
  310. }
  311. /**
  312. * Get all the public constructors of this class. This returns an array of
  313. * length 0 if there are no constructors, including for primitive types,
  314. * arrays, and interfaces. It does, however, include the default
  315. * constructor if one was supplied by the compiler. A security check may
  316. * be performed, with <code>checkMemberAccess(this, Member.PUBLIC)</code>
  317. * as well as <code>checkPackageAccess</code> both having to succeed.
  318. *
  319. * @return all public constructors in this class
  320. * @throws SecurityException if the security check fails
  321. * @since 1.1
  322. */
  323. public Constructor<?>[] getConstructors()
  324. {
  325. memberAccessCheck(Member.PUBLIC);
  326. return getDeclaredConstructors(true);
  327. }
  328. /**
  329. * Get a constructor declared in this class. If the constructor takes no
  330. * argument, an array of zero elements and null are equivalent for the
  331. * types argument. A security check may be performed, with
  332. * <code>checkMemberAccess(this, Member.DECLARED)</code> as well as
  333. * <code>checkPackageAccess</code> both having to succeed.
  334. *
  335. * @param types the type of each parameter
  336. * @return the constructor
  337. * @throws NoSuchMethodException if the constructor does not exist
  338. * @throws SecurityException if the security check fails
  339. * @see #getDeclaredConstructors()
  340. * @since 1.1
  341. */
  342. public Constructor<T> getDeclaredConstructor(Class<?>... types)
  343. throws NoSuchMethodException
  344. {
  345. memberAccessCheck(Member.DECLARED);
  346. Constructor[] constructors = getDeclaredConstructors(false);
  347. for (int i = 0; i < constructors.length; i++)
  348. {
  349. Constructor constructor = constructors[i];
  350. if (matchParameters(types, constructor.getParameterTypes()))
  351. return constructor;
  352. }
  353. throw new NoSuchMethodException();
  354. }
  355. /**
  356. * Get all the declared member classes and interfaces in this class, but
  357. * not those inherited from superclasses. This returns an array of length
  358. * 0 if there are no member classes, including for primitive types. A
  359. * security check may be performed, with
  360. * <code>checkMemberAccess(this, Member.DECLARED)</code> as well as
  361. * <code>checkPackageAccess</code> both having to succeed.
  362. *
  363. * @return all declared member classes in this class
  364. * @throws SecurityException if the security check fails
  365. * @since 1.1
  366. */
  367. public Class<?>[] getDeclaredClasses()
  368. {
  369. memberAccessCheck(Member.DECLARED);
  370. return getDeclaredClasses(false);
  371. }
  372. Class<?>[] getDeclaredClasses (boolean publicOnly)
  373. {
  374. return VMClass.getDeclaredClasses (this, publicOnly);
  375. }
  376. /**
  377. * Get all the declared constructors of this class. This returns an array of
  378. * length 0 if there are no constructors, including for primitive types,
  379. * arrays, and interfaces. It does, however, include the default
  380. * constructor if one was supplied by the compiler. A security check may
  381. * be performed, with <code>checkMemberAccess(this, Member.DECLARED)</code>
  382. * as well as <code>checkPackageAccess</code> both having to succeed.
  383. *
  384. * @return all constructors in this class
  385. * @throws SecurityException if the security check fails
  386. * @since 1.1
  387. */
  388. public Constructor<?>[] getDeclaredConstructors()
  389. {
  390. memberAccessCheck(Member.DECLARED);
  391. return getDeclaredConstructors(false);
  392. }
  393. Constructor<?>[] getDeclaredConstructors (boolean publicOnly)
  394. {
  395. return VMClass.getDeclaredConstructors (this, publicOnly);
  396. }
  397. /**
  398. * Get a field declared in this class, where name is its simple name. The
  399. * implicit length field of arrays is not available. A security check may
  400. * be performed, with <code>checkMemberAccess(this, Member.DECLARED)</code>
  401. * as well as <code>checkPackageAccess</code> both having to succeed.
  402. *
  403. * @param name the name of the field
  404. * @return the field
  405. * @throws NoSuchFieldException if the field does not exist
  406. * @throws SecurityException if the security check fails
  407. * @throws NullPointerException if <code>fieldName</code> is null
  408. * @see #getDeclaredFields()
  409. * @since 1.1
  410. */
  411. public Field getDeclaredField(String name) throws NoSuchFieldException
  412. {
  413. if (name == null)
  414. throw new NullPointerException();
  415. memberAccessCheck(Member.DECLARED);
  416. Field[] fields = getDeclaredFields(false);
  417. for (int i = 0; i < fields.length; i++)
  418. {
  419. if (fields[i].getName().equals(name))
  420. return fields[i];
  421. }
  422. throw new NoSuchFieldException();
  423. }
  424. /**
  425. * Get all the declared fields in this class, but not those inherited from
  426. * superclasses. This returns an array of length 0 if there are no fields,
  427. * including for primitive types. This does not return the implicit length
  428. * field of arrays. A security check may be performed, with
  429. * <code>checkMemberAccess(this, Member.DECLARED)</code> as well as
  430. * <code>checkPackageAccess</code> both having to succeed.
  431. *
  432. * @return all declared fields in this class
  433. * @throws SecurityException if the security check fails
  434. * @since 1.1
  435. */
  436. public Field[] getDeclaredFields()
  437. {
  438. memberAccessCheck(Member.DECLARED);
  439. return getDeclaredFields(false);
  440. }
  441. Field[] getDeclaredFields (boolean publicOnly)
  442. {
  443. return VMClass.getDeclaredFields (this, publicOnly);
  444. }
  445. /**
  446. * Get a method declared in this class, where name is its simple name. The
  447. * implicit methods of Object are not available from arrays or interfaces.
  448. * Constructors (named "&lt;init&gt;" in the class file) and class initializers
  449. * (name "&lt;clinit&gt;") are not available. The Virtual Machine allows
  450. * multiple methods with the same signature but differing return types; in
  451. * such a case the most specific return types are favored, then the final
  452. * choice is arbitrary. If the method takes no argument, an array of zero
  453. * elements and null are equivalent for the types argument. A security
  454. * check may be performed, with
  455. * <code>checkMemberAccess(this, Member.DECLARED)</code> as well as
  456. * <code>checkPackageAccess</code> both having to succeed.
  457. *
  458. * @param methodName the name of the method
  459. * @param types the type of each parameter
  460. * @return the method
  461. * @throws NoSuchMethodException if the method does not exist
  462. * @throws SecurityException if the security check fails
  463. * @throws NullPointerException if <code>methodName</code> is null
  464. * @see #getDeclaredMethods()
  465. * @since 1.1
  466. */
  467. public Method getDeclaredMethod(String methodName, Class<?>... types)
  468. throws NoSuchMethodException
  469. {
  470. if (methodName == null)
  471. throw new NullPointerException();
  472. memberAccessCheck(Member.DECLARED);
  473. Method match = matchMethod(getDeclaredMethods(false), methodName, types);
  474. if (match == null)
  475. throw new NoSuchMethodException(methodName);
  476. return match;
  477. }
  478. /**
  479. * Get all the declared methods in this class, but not those inherited from
  480. * superclasses. This returns an array of length 0 if there are no methods,
  481. * including for primitive types. This does include the implicit methods of
  482. * arrays and interfaces which mirror methods of Object, nor does it
  483. * include constructors or the class initialization methods. The Virtual
  484. * Machine allows multiple methods with the same signature but differing
  485. * return types; all such methods are in the returned array. A security
  486. * check may be performed, with
  487. * <code>checkMemberAccess(this, Member.DECLARED)</code> as well as
  488. * <code>checkPackageAccess</code> both having to succeed.
  489. *
  490. * @return all declared methods in this class
  491. * @throws SecurityException if the security check fails
  492. * @since 1.1
  493. */
  494. public Method[] getDeclaredMethods()
  495. {
  496. memberAccessCheck(Member.DECLARED);
  497. return getDeclaredMethods(false);
  498. }
  499. Method[] getDeclaredMethods (boolean publicOnly)
  500. {
  501. return VMClass.getDeclaredMethods (this, publicOnly);
  502. }
  503. /**
  504. * If this is a nested or inner class, return the class that declared it.
  505. * If not, return null.
  506. *
  507. * @return the declaring class of this class
  508. * @since 1.1
  509. */
  510. public Class<?> getDeclaringClass()
  511. {
  512. return VMClass.getDeclaringClass (this);
  513. }
  514. /**
  515. * Get a public field declared or inherited in this class, where name is
  516. * its simple name. If the class contains multiple accessible fields by
  517. * that name, an arbitrary one is returned. The implicit length field of
  518. * arrays is not available. A security check may be performed, with
  519. * <code>checkMemberAccess(this, Member.PUBLIC)</code> as well as
  520. * <code>checkPackageAccess</code> both having to succeed.
  521. *
  522. * @param fieldName the name of the field
  523. * @return the field
  524. * @throws NoSuchFieldException if the field does not exist
  525. * @throws SecurityException if the security check fails
  526. * @throws NullPointerException if <code>fieldName</code> is null
  527. * @see #getFields()
  528. * @since 1.1
  529. */
  530. public Field getField(String fieldName)
  531. throws NoSuchFieldException
  532. {
  533. if (fieldName == null)
  534. throw new NullPointerException();
  535. memberAccessCheck(Member.PUBLIC);
  536. Field field = internalGetField(fieldName);
  537. if (field == null)
  538. throw new NoSuchFieldException(fieldName);
  539. return field;
  540. }
  541. /**
  542. * Get all the public fields declared in this class or inherited from
  543. * superclasses. This returns an array of length 0 if there are no fields,
  544. * including for primitive types. This does not return the implicit length
  545. * field of arrays. A security check may be performed, with
  546. * <code>checkMemberAccess(this, Member.PUBLIC)</code> as well as
  547. * <code>checkPackageAccess</code> both having to succeed.
  548. *
  549. * @return all public fields in this class
  550. * @throws SecurityException if the security check fails
  551. * @since 1.1
  552. */
  553. public Field[] getFields()
  554. {
  555. memberAccessCheck(Member.PUBLIC);
  556. return internalGetFields();
  557. }
  558. /**
  559. * Like <code>getFields()</code> but without the security checks.
  560. */
  561. private Field[] internalGetFields()
  562. {
  563. LinkedHashSet<Field> set = new LinkedHashSet<Field>();
  564. set.addAll(Arrays.asList(getDeclaredFields(true)));
  565. Class[] interfaces = getInterfaces();
  566. for (int i = 0; i < interfaces.length; i++)
  567. set.addAll(Arrays.asList(interfaces[i].internalGetFields()));
  568. Class superClass = getSuperclass();
  569. if (superClass != null)
  570. set.addAll(Arrays.asList(superClass.internalGetFields()));
  571. return set.toArray(new Field[set.size()]);
  572. }
  573. /**
  574. * Returns the <code>Package</code> in which this class is defined
  575. * Returns null when this information is not available from the
  576. * classloader of this class.
  577. *
  578. * @return the package for this class, if it is available
  579. * @since 1.2
  580. */
  581. public Package getPackage()
  582. {
  583. ClassLoader cl = getClassLoader();
  584. if (cl != null)
  585. return cl.getPackage(getPackagePortion(getName()));
  586. else
  587. return VMClassLoader.getPackage(getPackagePortion(getName()));
  588. }
  589. /**
  590. * Get the interfaces this class <em>directly</em> implements, in the
  591. * order that they were declared. This returns an empty array, not null,
  592. * for Object, primitives, void, and classes or interfaces with no direct
  593. * superinterface. Array types return Cloneable and Serializable.
  594. *
  595. * @return the interfaces this class directly implements
  596. */
  597. public Class<?>[] getInterfaces()
  598. {
  599. return VMClass.getInterfaces (this);
  600. }
  601. private static final class MethodKey
  602. {
  603. private String name;
  604. private Class[] params;
  605. private Class returnType;
  606. private int hash;
  607. MethodKey(Method m)
  608. {
  609. name = m.getName();
  610. params = m.getParameterTypes();
  611. returnType = m.getReturnType();
  612. hash = name.hashCode() ^ returnType.hashCode();
  613. for(int i = 0; i < params.length; i++)
  614. {
  615. hash ^= params[i].hashCode();
  616. }
  617. }
  618. public boolean equals(Object o)
  619. {
  620. if (o instanceof MethodKey)
  621. {
  622. MethodKey m = (MethodKey) o;
  623. if (m.name.equals(name) && m.params.length == params.length
  624. && m.returnType == returnType)
  625. {
  626. for (int i = 0; i < params.length; i++)
  627. {
  628. if (m.params[i] != params[i])
  629. return false;
  630. }
  631. return true;
  632. }
  633. }
  634. return false;
  635. }
  636. public int hashCode()
  637. {
  638. return hash;
  639. }
  640. }
  641. /**
  642. * Get a public method declared or inherited in this class, where name is
  643. * its simple name. The implicit methods of Object are not available from
  644. * interfaces. Constructors (named "&lt;init&gt;" in the class file) and class
  645. * initializers (name "&lt;clinit&gt;") are not available. The Virtual
  646. * Machine allows multiple methods with the same signature but differing
  647. * return types, and the class can inherit multiple methods of the same
  648. * return type; in such a case the most specific return types are favored,
  649. * then the final choice is arbitrary. If the method takes no argument, an
  650. * array of zero elements and null are equivalent for the types argument.
  651. * A security check may be performed, with
  652. * <code>checkMemberAccess(this, Member.PUBLIC)</code> as well as
  653. * <code>checkPackageAccess</code> both having to succeed.
  654. *
  655. * @param methodName the name of the method
  656. * @param types the type of each parameter
  657. * @return the method
  658. * @throws NoSuchMethodException if the method does not exist
  659. * @throws SecurityException if the security check fails
  660. * @throws NullPointerException if <code>methodName</code> is null
  661. * @see #getMethods()
  662. * @since 1.1
  663. */
  664. public Method getMethod(String methodName, Class<?>... types)
  665. throws NoSuchMethodException
  666. {
  667. if (methodName == null)
  668. throw new NullPointerException();
  669. memberAccessCheck(Member.PUBLIC);
  670. Method method = internalGetMethod(methodName, types);
  671. if (method == null)
  672. throw new NoSuchMethodException(methodName);
  673. return method;
  674. }
  675. /**
  676. * Like <code>getMethod(String,Class[])</code> but without the security
  677. * checks and returns null instead of throwing NoSuchMethodException.
  678. */
  679. private Method internalGetMethod(String methodName, Class[] args)
  680. {
  681. Method match = matchMethod(getDeclaredMethods(true), methodName, args);
  682. if (match != null)
  683. return match;
  684. Class superClass = getSuperclass();
  685. if (superClass != null)
  686. {
  687. match = superClass.internalGetMethod(methodName, args);
  688. if(match != null)
  689. return match;
  690. }
  691. Class[] interfaces = getInterfaces();
  692. for (int i = 0; i < interfaces.length; i++)
  693. {
  694. match = interfaces[i].internalGetMethod(methodName, args);
  695. if (match != null)
  696. return match;
  697. }
  698. return null;
  699. }
  700. /**
  701. * Find the best matching method in <code>list</code> according to
  702. * the definition of ``best matching'' used by <code>getMethod()</code>
  703. *
  704. * <p>
  705. * Returns the method if any, otherwise <code>null</code>.
  706. *
  707. * @param list List of methods to search
  708. * @param name Name of method
  709. * @param args Method parameter types
  710. * @see #getMethod(String, Class[])
  711. */
  712. private static Method matchMethod(Method[] list, String name, Class[] args)
  713. {
  714. Method match = null;
  715. for (int i = 0; i < list.length; i++)
  716. {
  717. Method method = list[i];
  718. if (!method.getName().equals(name))
  719. continue;
  720. if (!matchParameters(args, method.getParameterTypes()))
  721. continue;
  722. if (match == null
  723. || match.getReturnType().isAssignableFrom(method.getReturnType()))
  724. match = method;
  725. }
  726. return match;
  727. }
  728. /**
  729. * Check for an exact match between parameter type lists.
  730. * Either list may be <code>null</code> to mean a list of
  731. * length zero.
  732. */
  733. private static boolean matchParameters(Class[] types1, Class[] types2)
  734. {
  735. if (types1 == null)
  736. return types2 == null || types2.length == 0;
  737. if (types2 == null)
  738. return types1 == null || types1.length == 0;
  739. if (types1.length != types2.length)
  740. return false;
  741. for (int i = 0; i < types1.length; i++)
  742. {
  743. if (types1[i] != types2[i])
  744. return false;
  745. }
  746. return true;
  747. }
  748. /**
  749. * Get all the public methods declared in this class or inherited from
  750. * superclasses. This returns an array of length 0 if there are no methods,
  751. * including for primitive types. This does not include the implicit
  752. * methods of interfaces which mirror methods of Object, nor does it
  753. * include constructors or the class initialization methods. The Virtual
  754. * Machine allows multiple methods with the same signature but differing
  755. * return types; all such methods are in the returned array. A security
  756. * check may be performed, with
  757. * <code>checkMemberAccess(this, Member.PUBLIC)</code> as well as
  758. * <code>checkPackageAccess</code> both having to succeed.
  759. *
  760. * @return all public methods in this class
  761. * @throws SecurityException if the security check fails
  762. * @since 1.1
  763. */
  764. public Method[] getMethods()
  765. {
  766. memberAccessCheck(Member.PUBLIC);
  767. // NOTE the API docs claim that no methods are returned for arrays,
  768. // but Sun's implementation *does* return the public methods of Object
  769. // (as would be expected), so we follow their implementation instead
  770. // of their documentation.
  771. return internalGetMethods();
  772. }
  773. /**
  774. * Like <code>getMethods()</code> but without the security checks.
  775. */
  776. private Method[] internalGetMethods()
  777. {
  778. HashMap<MethodKey,Method> map = new HashMap<MethodKey,Method>();
  779. Method[] methods;
  780. Class[] interfaces = getInterfaces();
  781. for(int i = 0; i < interfaces.length; i++)
  782. {
  783. methods = interfaces[i].internalGetMethods();
  784. for(int j = 0; j < methods.length; j++)
  785. {
  786. map.put(new MethodKey(methods[j]), methods[j]);
  787. }
  788. }
  789. Class superClass = getSuperclass();
  790. if(superClass != null)
  791. {
  792. methods = superClass.internalGetMethods();
  793. for(int i = 0; i < methods.length; i++)
  794. {
  795. map.put(new MethodKey(methods[i]), methods[i]);
  796. }
  797. }
  798. methods = getDeclaredMethods(true);
  799. for(int i = 0; i < methods.length; i++)
  800. {
  801. map.put(new MethodKey(methods[i]), methods[i]);
  802. }
  803. return map.values().toArray(new Method[map.size()]);
  804. }
  805. /**
  806. * Get the modifiers of this class. These can be decoded using Modifier,
  807. * and is limited to one of public, protected, or private, and any of
  808. * final, static, abstract, or interface. An array class has the same
  809. * public, protected, or private modifier as its component type, and is
  810. * marked final but not an interface. Primitive types and void are marked
  811. * public and final, but not an interface.
  812. *
  813. * @return the modifiers of this class
  814. * @see Modifier
  815. * @since 1.1
  816. */
  817. public int getModifiers()
  818. {
  819. int mod = VMClass.getModifiers (this, false);
  820. return (mod & (Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE |
  821. Modifier.FINAL | Modifier.STATIC | Modifier.ABSTRACT |
  822. Modifier.INTERFACE));
  823. }
  824. /**
  825. * Get the name of this class, separated by dots for package separators.
  826. * If the class represents a primitive type, or void, then the
  827. * name of the type as it appears in the Java programming language
  828. * is returned. For instance, <code>Byte.TYPE.getName()</code>
  829. * returns "byte".
  830. *
  831. * Arrays are specially encoded as shown on this table.
  832. * <pre>
  833. * array type [<em>element type</em>
  834. * (note that the element type is encoded per
  835. * this table)
  836. * boolean Z
  837. * byte B
  838. * char C
  839. * short S
  840. * int I
  841. * long J
  842. * float F
  843. * double D
  844. * void V
  845. * class or interface, alone: &lt;dotted name&gt;
  846. * class or interface, as element type: L&lt;dotted name&gt;;
  847. * </pre>
  848. *
  849. * @return the name of this class
  850. */
  851. public String getName()
  852. {
  853. return VMClass.getName (this);
  854. }
  855. /**
  856. * Get a resource URL using this class's package using the
  857. * getClassLoader().getResource() method. If this class was loaded using
  858. * the system classloader, ClassLoader.getSystemResource() is used instead.
  859. *
  860. * <p>If the name you supply is absolute (it starts with a <code>/</code>),
  861. * then the leading <code>/</code> is removed and it is passed on to
  862. * getResource(). If it is relative, the package name is prepended, and
  863. * <code>.</code>'s are replaced with <code>/</code>.
  864. *
  865. * <p>The URL returned is system- and classloader-dependent, and could
  866. * change across implementations.
  867. *
  868. * @param resourceName the name of the resource, generally a path
  869. * @return the URL to the resource
  870. * @throws NullPointerException if name is null
  871. * @since 1.1
  872. */
  873. public URL getResource(String resourceName)
  874. {
  875. String name = resourcePath(resourceName);
  876. ClassLoader loader = getClassLoader();
  877. if (loader == null)
  878. return ClassLoader.getSystemResource(name);
  879. return loader.getResource(name);
  880. }
  881. /**
  882. * Get a resource using this class's package using the
  883. * getClassLoader().getResourceAsStream() method. If this class was loaded
  884. * using the system classloader, ClassLoader.getSystemResource() is used
  885. * instead.
  886. *
  887. * <p>If the name you supply is absolute (it starts with a <code>/</code>),
  888. * then the leading <code>/</code> is removed and it is passed on to
  889. * getResource(). If it is relative, the package name is prepended, and
  890. * <code>.</code>'s are replaced with <code>/</code>.
  891. *
  892. * <p>The URL returned is system- and classloader-dependent, and could
  893. * change across implementations.
  894. *
  895. * @param resourceName the name of the resource, generally a path
  896. * @return an InputStream with the contents of the resource in it, or null
  897. * @throws NullPointerException if name is null
  898. * @since 1.1
  899. */
  900. public InputStream getResourceAsStream(String resourceName)
  901. {
  902. String name = resourcePath(resourceName);
  903. ClassLoader loader = getClassLoader();
  904. if (loader == null)
  905. return ClassLoader.getSystemResourceAsStream(name);
  906. return loader.getResourceAsStream(name);
  907. }
  908. private String resourcePath(String resourceName)
  909. {
  910. if (resourceName.length() > 0)
  911. {
  912. if (resourceName.charAt(0) != '/')
  913. {
  914. String pkg = getPackagePortion(getName());
  915. if (pkg.length() > 0)
  916. resourceName = pkg.replace('.','/') + '/' + resourceName;
  917. }
  918. else
  919. {
  920. resourceName = resourceName.substring(1);
  921. }
  922. }
  923. return resourceName;
  924. }
  925. /**
  926. * Get the signers of this class. This returns null if there are no signers,
  927. * such as for primitive types or void.
  928. *
  929. * @return the signers of this class
  930. * @since 1.1
  931. */
  932. public Object[] getSigners()
  933. {
  934. return signers == null ? null : (Object[]) signers.clone ();
  935. }
  936. /**
  937. * Set the signers of this class.
  938. *
  939. * @param signers the signers of this class
  940. */
  941. void setSigners(Object[] signers)
  942. {
  943. this.signers = signers;
  944. }
  945. /**
  946. * Get the direct superclass of this class. If this is an interface,
  947. * Object, a primitive type, or void, it will return null. If this is an
  948. * array type, it will return Object.
  949. *
  950. * @return the direct superclass of this class
  951. */
  952. public Class<? super T> getSuperclass()
  953. {
  954. return VMClass.getSuperclass (this);
  955. }
  956. /**
  957. * Return whether this class is an array type.
  958. *
  959. * @return whether this class is an array type
  960. * @since 1.1
  961. */
  962. public boolean isArray()
  963. {
  964. return VMClass.isArray (this);
  965. }
  966. /**
  967. * Discover whether an instance of the Class parameter would be an
  968. * instance of this Class as well. Think of doing
  969. * <code>isInstance(c.newInstance())</code> or even
  970. * <code>c.newInstance() instanceof (this class)</code>. While this
  971. * checks widening conversions for objects, it must be exact for primitive
  972. * types.
  973. *
  974. * @param c the class to check
  975. * @return whether an instance of c would be an instance of this class
  976. * as well
  977. * @throws NullPointerException if c is null
  978. * @since 1.1
  979. */
  980. public boolean isAssignableFrom(Class<?> c)
  981. {
  982. return VMClass.isAssignableFrom (this, c);
  983. }
  984. /**
  985. * Discover whether an Object is an instance of this Class. Think of it
  986. * as almost like <code>o instanceof (this class)</code>.
  987. *
  988. * @param o the Object to check
  989. * @return whether o is an instance of this class
  990. * @since 1.1
  991. */
  992. public boolean isInstance(Object o)
  993. {
  994. return VMClass.isInstance (this, o);
  995. }
  996. /**
  997. * Check whether this class is an interface or not. Array types are not
  998. * interfaces.
  999. *
  1000. * @return whether this class is an interface or not
  1001. */
  1002. public boolean isInterface()
  1003. {
  1004. return VMClass.isInterface (this);
  1005. }
  1006. /**
  1007. * Return whether this class is a primitive type. A primitive type class
  1008. * is a class representing a kind of "placeholder" for the various
  1009. * primitive types, or void. You can access the various primitive type
  1010. * classes through java.lang.Boolean.TYPE, java.lang.Integer.TYPE, etc.,
  1011. * or through boolean.class, int.class, etc.
  1012. *
  1013. * @return whether this class is a primitive type
  1014. * @see Boolean#TYPE
  1015. * @see Byte#TYPE
  1016. * @see Character#TYPE
  1017. * @see Short#TYPE
  1018. * @see Integer#TYPE
  1019. * @see Long#TYPE
  1020. * @see Float#TYPE
  1021. * @see Double#TYPE
  1022. * @see Void#TYPE
  1023. * @since 1.1
  1024. */
  1025. public boolean isPrimitive()
  1026. {
  1027. return VMClass.isPrimitive (this);
  1028. }
  1029. /**
  1030. * Get a new instance of this class by calling the no-argument constructor.
  1031. * The class is initialized if it has not been already. A security check
  1032. * may be performed, with <code>checkMemberAccess(this, Member.PUBLIC)</code>
  1033. * as well as <code>checkPackageAccess</code> both having to succeed.
  1034. *
  1035. * @return a new instance of this class
  1036. * @throws InstantiationException if there is not a no-arg constructor
  1037. * for this class, including interfaces, abstract classes, arrays,
  1038. * primitive types, and void; or if an exception occurred during
  1039. * the constructor
  1040. * @throws IllegalAccessException if you are not allowed to access the
  1041. * no-arg constructor because of scoping reasons
  1042. * @throws SecurityException if the security check fails
  1043. * @throws ExceptionInInitializerError if class initialization caused by
  1044. * this call fails with an exception
  1045. */
  1046. public T newInstance()
  1047. throws InstantiationException, IllegalAccessException
  1048. {
  1049. memberAccessCheck(Member.PUBLIC);
  1050. Constructor<T> constructor;
  1051. synchronized(this)
  1052. {
  1053. constructor = this.constructor;
  1054. }
  1055. if (constructor == null)
  1056. {
  1057. Constructor[] constructors = getDeclaredConstructors(false);
  1058. for (int i = 0; i < constructors.length; i++)
  1059. {
  1060. if (constructors[i].getParameterTypes().length == 0)
  1061. {
  1062. constructor = constructors[i];
  1063. break;
  1064. }
  1065. }
  1066. if (constructor == null)
  1067. throw new InstantiationException(getName());
  1068. if (!Modifier.isPublic(constructor.getModifiers())
  1069. || !Modifier.isPublic(VMClass.getModifiers(this, true)))
  1070. {
  1071. setAccessible(constructor);
  1072. }
  1073. synchronized(this)
  1074. {
  1075. if (this.constructor == null)
  1076. this.constructor = constructor;
  1077. }
  1078. }
  1079. int modifiers = constructor.getModifiers();
  1080. if (!Modifier.isPublic(modifiers)
  1081. || !Modifier.isPublic(VMClass.getModifiers(this, true)))
  1082. {
  1083. Class caller = VMStackWalker.getCallingClass();
  1084. if (caller != null &&
  1085. caller != this &&
  1086. (Modifier.isPrivate(modifiers)
  1087. || getClassLoader() != caller.getClassLoader()
  1088. || !getPackagePortion(getName())
  1089. .equals(getPackagePortion(caller.getName()))))
  1090. throw new IllegalAccessException(getName()
  1091. + " has an inaccessible constructor");
  1092. }
  1093. try
  1094. {
  1095. return constructor.newInstance();
  1096. }
  1097. catch (InvocationTargetException e)
  1098. {
  1099. VMClass.throwException(e.getTargetException());
  1100. throw (InternalError) new InternalError
  1101. ("VMClass.throwException returned").initCause(e);
  1102. }
  1103. }
  1104. /**
  1105. * Returns the protection domain of this class. If the classloader did not
  1106. * record the protection domain when creating this class the unknown
  1107. * protection domain is returned which has a <code>null</code> code source
  1108. * and all permissions. A security check may be performed, with
  1109. * <code>RuntimePermission("getProtectionDomain")</code>.
  1110. *
  1111. * @return the protection domain
  1112. * @throws SecurityException if the security manager exists and the caller
  1113. * does not have <code>RuntimePermission("getProtectionDomain")</code>.
  1114. * @see RuntimePermission
  1115. * @since 1.2
  1116. */
  1117. public ProtectionDomain getProtectionDomain()
  1118. {
  1119. SecurityManager sm = SecurityManager.current;
  1120. if (sm != null)
  1121. sm.checkPermission(new RuntimePermission("getProtectionDomain"));
  1122. return pd == null ? StaticData.unknownProtectionDomain : pd;
  1123. }
  1124. /**
  1125. * Return the human-readable form of this Object. For an object, this
  1126. * is either "interface " or "class " followed by <code>getName()</code>,
  1127. * for primitive types and void it is just <code>getName()</code>.
  1128. *
  1129. * @return the human-readable form of this Object
  1130. */
  1131. public String toString()
  1132. {
  1133. if (isPrimitive())
  1134. return getName();
  1135. return (isInterface() ? "interface " : "class ") + getName();
  1136. }
  1137. /**
  1138. * Returns the desired assertion status of this class, if it were to be
  1139. * initialized at this moment. The class assertion status, if set, is
  1140. * returned; the backup is the default package status; then if there is
  1141. * a class loader, that default is returned; and finally the system default
  1142. * is returned. This method seldom needs calling in user code, but exists
  1143. * for compilers to implement the assert statement. Note that there is no
  1144. * guarantee that the result of this method matches the class's actual
  1145. * assertion status.
  1146. *
  1147. * @return the desired assertion status
  1148. * @see ClassLoader#setClassAssertionStatus(String, boolean)
  1149. * @see ClassLoader#setPackageAssertionStatus(String, boolean)
  1150. * @see ClassLoader#setDefaultAssertionStatus(boolean)
  1151. * @since 1.4
  1152. */
  1153. public boolean desiredAssertionStatus()
  1154. {
  1155. ClassLoader c = getClassLoader();
  1156. Object status;
  1157. if (c == null)
  1158. return VMClassLoader.defaultAssertionStatus();
  1159. if (c.classAssertionStatus != null)
  1160. synchronized (c)
  1161. {
  1162. status = c.classAssertionStatus.get(getName());
  1163. if (status != null)
  1164. return status.equals(Boolean.TRUE);
  1165. }
  1166. else
  1167. {
  1168. status = ClassLoader.StaticData.
  1169. systemClassAssertionStatus.get(getName());
  1170. if (status != null)
  1171. return status.equals(Boolean.TRUE);
  1172. }
  1173. if (c.packageAssertionStatus != null)
  1174. synchronized (c)
  1175. {
  1176. String name = getPackagePortion(getName());
  1177. if ("".equals(name))
  1178. status = c.packageAssertionStatus.get(null);
  1179. else
  1180. do
  1181. {
  1182. status = c.packageAssertionStatus.get(name);
  1183. name = getPackagePortion(name);
  1184. }
  1185. while (! "".equals(name) && status == null);
  1186. if (status != null)
  1187. return status.equals(Boolean.TRUE);
  1188. }
  1189. else
  1190. {
  1191. String name = getPackagePortion(getName());
  1192. if ("".equals(name))
  1193. status = ClassLoader.StaticData.
  1194. systemPackageAssertionStatus.get(null);
  1195. else
  1196. do
  1197. {
  1198. status = ClassLoader.StaticData.
  1199. systemPackageAssertionStatus.get(name);
  1200. name = getPackagePortion(name);
  1201. }
  1202. while (! "".equals(name) && status == null);
  1203. if (status != null)
  1204. return status.equals(Boolean.TRUE);
  1205. }
  1206. return c.defaultAssertionStatus;
  1207. }
  1208. /**
  1209. * <p>
  1210. * Casts this class to represent a subclass of the specified class.
  1211. * This method is useful for `narrowing' the type of a class so that
  1212. * the class object, and instances of that class, can match the contract
  1213. * of a more restrictive method. For example, if this class has the
  1214. * static type of <code>Class&lt;Object&gt;</code>, and a dynamic type of
  1215. * <code>Class&lt;Rectangle&gt;</code>, then, assuming <code>Shape</code> is
  1216. * a superclass of <code>Rectangle</code>, this method can be used on
  1217. * this class with the parameter, <code>Class&lt;Shape&gt;</code>, to retain
  1218. * the same instance but with the type
  1219. * <code>Class&lt;? extends Shape&gt;</code>.
  1220. * </p>
  1221. * <p>
  1222. * If this class can be converted to an instance which is parameterised
  1223. * over a subtype of the supplied type, <code>U</code>, then this method
  1224. * returns an appropriately cast reference to this object. Otherwise,
  1225. * a <code>ClassCastException</code> is thrown.
  1226. * </p>
  1227. *
  1228. * @param klass the class object, the parameterized type (<code>U</code>) of
  1229. * which should be a superclass of the parameterized type of
  1230. * this instance.
  1231. * @return a reference to this object, appropriately cast.
  1232. * @throws ClassCastException if this class can not be converted to one
  1233. * which represents a subclass of the specified
  1234. * type, <code>U</code>.
  1235. * @since 1.5
  1236. */
  1237. public <U> Class<? extends U> asSubclass(Class<U> klass)
  1238. {
  1239. if (! klass.isAssignableFrom(this))
  1240. throw new ClassCastException();
  1241. return (Class<? extends U>) this;
  1242. }
  1243. /**
  1244. * Returns the specified object, cast to this <code>Class</code>' type.
  1245. *
  1246. * @param obj the object to cast
  1247. * @throws ClassCastException if obj is not an instance of this class
  1248. * @since 1.5
  1249. */
  1250. public T cast(Object obj)
  1251. {
  1252. if (obj != null && ! isInstance(obj))
  1253. throw new ClassCastException();
  1254. return (T) obj;
  1255. }
  1256. /**
  1257. * Like <code>getField(String)</code> but without the security checks and
  1258. * returns null instead of throwing NoSuchFieldException.
  1259. */
  1260. private Field internalGetField(String name)
  1261. {
  1262. Field[] fields = getDeclaredFields(true);
  1263. for (int i = 0; i < fields.length; i++)
  1264. {
  1265. Field field = fields[i];
  1266. if (field.getName().equals(name))
  1267. return field;
  1268. }
  1269. Class[] interfaces = getInterfaces();
  1270. for (int i = 0; i < interfaces.length; i++)
  1271. {
  1272. Field field = interfaces[i].internalGetField(name);
  1273. if(field != null)
  1274. return field;
  1275. }
  1276. Class superClass = getSuperclass();
  1277. if (superClass != null)
  1278. return superClass.internalGetField(name);
  1279. return null;
  1280. }
  1281. /**
  1282. * Strip the last portion of the name (after the last dot).
  1283. *
  1284. * @param name the name to get package of
  1285. * @return the package name, or "" if no package
  1286. */
  1287. private static String getPackagePortion(String name)
  1288. {
  1289. int lastInd = name.lastIndexOf('.');
  1290. if (lastInd == -1)
  1291. return "";
  1292. return name.substring(0, lastInd);
  1293. }
  1294. /**
  1295. * Perform security checks common to all of the methods that
  1296. * get members of this Class.
  1297. */
  1298. private void memberAccessCheck(int which)
  1299. {
  1300. SecurityManager sm = SecurityManager.current;
  1301. if (sm != null)
  1302. {
  1303. sm.checkMemberAccess(this, which);
  1304. Package pkg = getPackage();
  1305. if (pkg != null)
  1306. sm.checkPackageAccess(pkg.getName());
  1307. }
  1308. }
  1309. /**
  1310. * Returns the enumeration constants of this class, or
  1311. * null if this class is not an <code>Enum</code>.
  1312. *
  1313. * @return an array of <code>Enum</code> constants
  1314. * associated with this class, or null if this
  1315. * class is not an <code>enum</code>.
  1316. * @since 1.5
  1317. */
  1318. public T[] getEnumConstants()
  1319. {
  1320. if (isEnum())
  1321. {
  1322. try
  1323. {
  1324. Method m = getMethod("values");
  1325. setAccessible(m);
  1326. return (T[]) m.invoke(null);
  1327. }
  1328. catch (NoSuchMethodException exception)
  1329. {
  1330. throw new Error("Enum lacks values() method");
  1331. }
  1332. catch (IllegalAccessException exception)
  1333. {
  1334. throw new Error("Unable to access Enum class");
  1335. }
  1336. catch (InvocationTargetException exception)
  1337. {
  1338. throw new
  1339. RuntimeException("The values method threw an exception",
  1340. exception);
  1341. }
  1342. }
  1343. else
  1344. {
  1345. return null;
  1346. }
  1347. }
  1348. /**
  1349. * Returns true if this class is an <code>Enum</code>.
  1350. *
  1351. * @return true if this is an enumeration class.
  1352. * @since 1.5
  1353. */
  1354. public boolean isEnum()
  1355. {
  1356. int mod = VMClass.getModifiers (this, true);
  1357. return (mod & ENUM) != 0;
  1358. }
  1359. /**
  1360. * Returns true if this class is a synthetic class, generated by
  1361. * the compiler.
  1362. *
  1363. * @return true if this is a synthetic class.
  1364. * @since 1.5
  1365. */
  1366. public boolean isSynthetic()
  1367. {
  1368. int mod = VMClass.getModifiers (this, true);
  1369. return (mod & SYNTHETIC) != 0;
  1370. }
  1371. /**
  1372. * Returns true if this class is an <code>Annotation</code>.
  1373. *
  1374. * @return true if this is an annotation class.
  1375. * @since 1.5
  1376. */
  1377. public boolean isAnnotation()
  1378. {
  1379. int mod = VMClass.getModifiers (this, true);
  1380. return (mod & ANNOTATION) != 0;
  1381. }
  1382. /**
  1383. * Returns the simple name for this class, as used in the source
  1384. * code. For normal classes, this is the content returned by
  1385. * <code>getName()</code> which follows the last ".". Anonymous
  1386. * classes have no name, and so the result of calling this method is
  1387. * "". The simple name of an array consists of the simple name of
  1388. * its component type, followed by "[]". Thus, an array with the
  1389. * component type of an anonymous class has a simple name of simply
  1390. * "[]".
  1391. *
  1392. * @return the simple name for this class.
  1393. * @since 1.5
  1394. */
  1395. public String getSimpleName()
  1396. {
  1397. return VMClass.getSimpleName(this);
  1398. }
  1399. /**
  1400. * Returns this class' annotation for the specified annotation type,
  1401. * or <code>null</code> if no such annotation exists.
  1402. *
  1403. * @param annotationClass the type of annotation to look for.
  1404. * @return this class' annotation for the specified type, or
  1405. * <code>null</code> if no such annotation exists.
  1406. * @since 1.5
  1407. */
  1408. public <A extends Annotation> A getAnnotation(Class<A> annotationClass)
  1409. {
  1410. A foundAnnotation = null;
  1411. Annotation[] annotations = getAnnotations();
  1412. for (Annotation annotation : annotations)
  1413. if (annotation.annotationType() == annotationClass)
  1414. foundAnnotation = (A) annotation;
  1415. return foundAnnotation;
  1416. }
  1417. /**
  1418. * Returns all annotations associated with this class. If there are
  1419. * no annotations associated with this class, then a zero-length array
  1420. * will be returned. The returned array may be modified by the client
  1421. * code, but this will have no effect on the annotation content of this
  1422. * class, and hence no effect on the return value of this method for
  1423. * future callers.
  1424. *
  1425. * @return this class' annotations.
  1426. * @since 1.5
  1427. */
  1428. public Annotation[] getAnnotations()
  1429. {
  1430. HashMap<Class, Annotation> map = new HashMap<Class, Annotation>();
  1431. for (Annotation a : getDeclaredAnnotations())
  1432. map.put((Class) a.annotationType(), a);
  1433. for (Class<? super T> s = getSuperclass();
  1434. s != null;
  1435. s = s.getSuperclass())
  1436. {
  1437. for (Annotation a : s.getDeclaredAnnotations())
  1438. {
  1439. Class k = (Class) a.annotationType();
  1440. if (! map.containsKey(k) && k.isAnnotationPresent(Inherited.class))
  1441. map.put(k, a);
  1442. }
  1443. }
  1444. Collection<Annotation> v = map.values();
  1445. return v.toArray(new Annotation[v.size()]);
  1446. }
  1447. /**
  1448. * <p>
  1449. * Returns the canonical name of this class, as defined by section
  1450. * 6.7 of the Java language specification. Each package, top-level class,
  1451. * top-level interface and primitive type has a canonical name. A member
  1452. * class has a canonical name, if its parent class has one. Likewise,
  1453. * an array type has a canonical name, if its component type does.
  1454. * Local or anonymous classes do not have canonical names.
  1455. * </p>
  1456. * <p>
  1457. * The canonical name for top-level classes, top-level interfaces and
  1458. * primitive types is always the same as the fully-qualified name.
  1459. * For array types, the canonical name is the canonical name of its
  1460. * component type with `[]' appended.
  1461. * </p>
  1462. * <p>
  1463. * The canonical name of a member class always refers to the place where
  1464. * the class was defined, and is composed of the canonical name of the
  1465. * defining class and the simple name of the member class, joined by `.'.
  1466. * For example, if a <code>Person</code> class has an inner class,
  1467. * <code>M</code>, then both its fully-qualified name and canonical name
  1468. * is <code>Person.M</code>. A subclass, <code>Staff</code>, of
  1469. * <code>Person</code> refers to the same inner class by the fully-qualified
  1470. * name of <code>Staff.M</code>, but its canonical name is still
  1471. * <code>Person.M</code>.
  1472. * </p>
  1473. * <p>
  1474. * Where no canonical name is present, <code>null</code> is returned.
  1475. * </p>
  1476. *
  1477. * @return the canonical name of the class, or <code>null</code> if the
  1478. * class doesn't have a canonical name.
  1479. * @since 1.5
  1480. */
  1481. public String getCanonicalName()
  1482. {
  1483. return VMClass.getCanonicalName(this);
  1484. }
  1485. /**
  1486. * Returns all annotations directly defined by this class. If there are
  1487. * no annotations associated with this class, then a zero-length array
  1488. * will be returned. The returned array may be modified by the client
  1489. * code, but this will have no effect on the annotation content of this
  1490. * class, and hence no effect on the return value of this method for
  1491. * future callers.
  1492. *
  1493. * @return the annotations directly defined by this class.
  1494. * @since 1.5
  1495. */
  1496. public Annotation[] getDeclaredAnnotations()
  1497. {
  1498. return VMClass.getDeclaredAnnotations(this);
  1499. }
  1500. /**
  1501. * Returns the class which immediately encloses this class. If this class
  1502. * is a top-level class, this method returns <code>null</code>.
  1503. *
  1504. * @return the immediate enclosing class, or <code>null</code> if this is
  1505. * a top-level class.
  1506. * @since 1.5
  1507. */
  1508. public Class<?> getEnclosingClass()
  1509. {
  1510. return VMClass.getEnclosingClass(this);
  1511. }
  1512. /**
  1513. * Returns the constructor which immediately encloses this class. If
  1514. * this class is a top-level class, or a local or anonymous class
  1515. * immediately enclosed by a type definition, instance initializer
  1516. * or static initializer, then <code>null</code> is returned.
  1517. *
  1518. * @return the immediate enclosing constructor if this class is
  1519. * declared within a constructor. Otherwise, <code>null</code>
  1520. * is returned.
  1521. * @since 1.5
  1522. */
  1523. public Constructor<?> getEnclosingConstructor()
  1524. {
  1525. return VMClass.getEnclosingConstructor(this);
  1526. }
  1527. /**
  1528. * Returns the method which immediately encloses this class. If
  1529. * this class is a top-level class, or a local or anonymous class
  1530. * immediately enclosed by a type definition, instance initializer
  1531. * or static initializer, then <code>null</code> is returned.
  1532. *
  1533. * @return the immediate enclosing method if this class is
  1534. * declared within a method. Otherwise, <code>null</code>
  1535. * is returned.
  1536. * @since 1.5
  1537. */
  1538. public Method getEnclosingMethod()
  1539. {
  1540. return VMClass.getEnclosingMethod(this);
  1541. }
  1542. /**
  1543. * <p>
  1544. * Returns an array of <code>Type</code> objects which represent the
  1545. * interfaces directly implemented by this class or extended by this
  1546. * interface.
  1547. * </p>
  1548. * <p>
  1549. * If one of the superinterfaces is a parameterized type, then the
  1550. * object returned for this interface reflects the actual type
  1551. * parameters used in the source code. Type parameters are created
  1552. * using the semantics specified by the <code>ParameterizedType</code>
  1553. * interface, and only if an instance has not already been created.
  1554. * </p>
  1555. * <p>
  1556. * The order of the interfaces in the array matches the order in which
  1557. * the interfaces are declared. For classes which represent an array,
  1558. * an array of two interfaces, <code>Cloneable</code> and
  1559. * <code>Serializable</code>, is always returned, with the objects in
  1560. * that order. A class representing a primitive type or void always
  1561. * returns an array of zero size.
  1562. * </p>
  1563. *
  1564. * @return an array of interfaces implemented or extended by this class.
  1565. * @throws GenericSignatureFormatError if the generic signature of one
  1566. * of the interfaces does not comply with that specified by the Java
  1567. * Virtual Machine specification, 3rd edition.
  1568. * @throws TypeNotPresentException if any of the superinterfaces refers
  1569. * to a non-existant type.
  1570. * @throws MalformedParameterizedTypeException if any of the interfaces
  1571. * refer to a parameterized type that can not be instantiated for
  1572. * some reason.
  1573. * @since 1.5
  1574. * @see java.lang.reflect.ParameterizedType
  1575. */
  1576. public Type[] getGenericInterfaces()
  1577. {
  1578. if (isPrimitive())
  1579. return new Type[0];
  1580. String sig = VMClass.getClassSignature(this);
  1581. if (sig == null)
  1582. return getInterfaces();
  1583. ClassSignatureParser p = new ClassSignatureParser(this, sig);
  1584. return p.getInterfaceTypes();
  1585. }
  1586. /**
  1587. * <p>
  1588. * Returns a <code>Type</code> object representing the direct superclass,
  1589. * whether class, interface, primitive type or void, of this class.
  1590. * If this class is an array class, then a class instance representing
  1591. * the <code>Object</code> class is returned. If this class is primitive,
  1592. * an interface, or a representation of either the <code>Object</code>
  1593. * class or void, then <code>null</code> is returned.
  1594. * </p>
  1595. * <p>
  1596. * If the superclass is a parameterized type, then the
  1597. * object returned for this interface reflects the actual type
  1598. * parameters used in the source code. Type parameters are created
  1599. * using the semantics specified by the <code>ParameterizedType</code>
  1600. * interface, and only if an instance has not already been created.
  1601. * </p>
  1602. *
  1603. * @return the superclass of this class.
  1604. * @throws GenericSignatureFormatError if the generic signature of the
  1605. * class does not comply with that specified by the Java
  1606. * Virtual Machine specification, 3rd edition.
  1607. * @throws TypeNotPresentException if the superclass refers
  1608. * to a non-existant type.
  1609. * @throws MalformedParameterizedTypeException if the superclass
  1610. * refers to a parameterized type that can not be instantiated for
  1611. * some reason.
  1612. * @since 1.5
  1613. * @see java.lang.reflect.ParameterizedType
  1614. */
  1615. public Type getGenericSuperclass()
  1616. {
  1617. if (isArray())
  1618. return Object.class;
  1619. if (isPrimitive() || isInterface() || this == Object.class)
  1620. return null;
  1621. String sig = VMClass.getClassSignature(this);
  1622. if (sig == null)
  1623. return getSuperclass();
  1624. ClassSignatureParser p = new ClassSignatureParser(this, sig);
  1625. return p.getSuperclassType();
  1626. }
  1627. /**
  1628. * Returns an array of <code>TypeVariable</code> objects that represents
  1629. * the type variables declared by this class, in declaration order.
  1630. * An array of size zero is returned if this class has no type
  1631. * variables.
  1632. *
  1633. * @return the type variables associated with this class.
  1634. * @throws GenericSignatureFormatError if the generic signature does
  1635. * not conform to the format specified in the Virtual Machine
  1636. * specification, version 3.
  1637. * @since 1.5
  1638. */
  1639. public TypeVariable<Class<T>>[] getTypeParameters()
  1640. {
  1641. String sig = VMClass.getClassSignature(this);
  1642. if (sig == null)
  1643. return (TypeVariable<Class<T>>[])new TypeVariable[0];
  1644. ClassSignatureParser p = new ClassSignatureParser(this, sig);
  1645. return p.getTypeParameters();
  1646. }
  1647. /**
  1648. * Returns true if an annotation for the specified type is associated
  1649. * with this class. This is primarily a short-hand for using marker
  1650. * annotations.
  1651. *
  1652. * @param annotationClass the type of annotation to look for.
  1653. * @return true if an annotation exists for the specified type.
  1654. * @since 1.5
  1655. */
  1656. public boolean isAnnotationPresent(Class<? extends Annotation>
  1657. annotationClass)
  1658. {
  1659. return getAnnotation(annotationClass) != null;
  1660. }
  1661. /**
  1662. * Returns true if this object represents an anonymous class.
  1663. *
  1664. * @return true if this object represents an anonymous class.
  1665. * @since 1.5
  1666. */
  1667. public boolean isAnonymousClass()
  1668. {
  1669. return VMClass.isAnonymousClass(this);
  1670. }
  1671. /**
  1672. * Returns true if this object represents an local class.
  1673. *
  1674. * @return true if this object represents an local class.
  1675. * @since 1.5
  1676. */
  1677. public boolean isLocalClass()
  1678. {
  1679. return VMClass.isLocalClass(this);
  1680. }
  1681. /**
  1682. * Returns true if this object represents an member class.
  1683. *
  1684. * @return true if this object represents an member class.
  1685. * @since 1.5
  1686. */
  1687. public boolean isMemberClass()
  1688. {
  1689. return VMClass.isMemberClass(this);
  1690. }
  1691. /**
  1692. * Utility method for use by classes in this package.
  1693. */
  1694. static void setAccessible(final AccessibleObject obj)
  1695. {
  1696. AccessController.doPrivileged(new PrivilegedAction()
  1697. {
  1698. public Object run()
  1699. {
  1700. obj.setAccessible(true);
  1701. return null;
  1702. }
  1703. });
  1704. }
  1705. }