Source for java.lang.Class

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