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