emul/mini/src/main/java/java/lang/Class.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Thu, 14 Feb 2013 13:17:19 +0100
changeset 733 25eba32a96cd
parent 643 a2c0afa35c09
child 747 ae352b763959
permissions -rw-r--r--
Fixing problems with Class.isAssignableFrom reported by David
     1 /*
     2  * Copyright (c) 1994, 2010, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Oracle designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Oracle in the LICENSE file that accompanied this code.
    10  *
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    14  * version 2 for more details (a copy is included in the LICENSE file that
    15  * accompanied this code).
    16  *
    17  * You should have received a copy of the GNU General Public License version
    18  * 2 along with this work; if not, write to the Free Software Foundation,
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    20  *
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    22  * or visit www.oracle.com if you need additional information or have any
    23  * questions.
    24  */
    25 
    26 package java.lang;
    27 
    28 import java.io.ByteArrayInputStream;
    29 import org.apidesign.bck2brwsr.emul.reflect.AnnotationImpl;
    30 import java.io.InputStream;
    31 import java.lang.annotation.Annotation;
    32 import java.lang.reflect.Field;
    33 import java.lang.reflect.Method;
    34 import java.lang.reflect.TypeVariable;
    35 import java.net.URL;
    36 import org.apidesign.bck2brwsr.core.JavaScriptBody;
    37 import org.apidesign.bck2brwsr.emul.reflect.MethodImpl;
    38 
    39 /**
    40  * Instances of the class {@code Class} represent classes and
    41  * interfaces in a running Java application.  An enum is a kind of
    42  * class and an annotation is a kind of interface.  Every array also
    43  * belongs to a class that is reflected as a {@code Class} object
    44  * that is shared by all arrays with the same element type and number
    45  * of dimensions.  The primitive Java types ({@code boolean},
    46  * {@code byte}, {@code char}, {@code short},
    47  * {@code int}, {@code long}, {@code float}, and
    48  * {@code double}), and the keyword {@code void} are also
    49  * represented as {@code Class} objects.
    50  *
    51  * <p> {@code Class} has no public constructor. Instead {@code Class}
    52  * objects are constructed automatically by the Java Virtual Machine as classes
    53  * are loaded and by calls to the {@code defineClass} method in the class
    54  * loader.
    55  *
    56  * <p> The following example uses a {@code Class} object to print the
    57  * class name of an object:
    58  *
    59  * <p> <blockquote><pre>
    60  *     void printClassName(Object obj) {
    61  *         System.out.println("The class of " + obj +
    62  *                            " is " + obj.getClass().getName());
    63  *     }
    64  * </pre></blockquote>
    65  *
    66  * <p> It is also possible to get the {@code Class} object for a named
    67  * type (or for void) using a class literal.  See Section 15.8.2 of
    68  * <cite>The Java&trade; Language Specification</cite>.
    69  * For example:
    70  *
    71  * <p> <blockquote>
    72  *     {@code System.out.println("The name of class Foo is: "+Foo.class.getName());}
    73  * </blockquote>
    74  *
    75  * @param <T> the type of the class modeled by this {@code Class}
    76  * object.  For example, the type of {@code String.class} is {@code
    77  * Class<String>}.  Use {@code Class<?>} if the class being modeled is
    78  * unknown.
    79  *
    80  * @author  unascribed
    81  * @see     java.lang.ClassLoader#defineClass(byte[], int, int)
    82  * @since   JDK1.0
    83  */
    84 public final
    85     class Class<T> implements java.io.Serializable,
    86                               java.lang.reflect.GenericDeclaration,
    87                               java.lang.reflect.Type,
    88                               java.lang.reflect.AnnotatedElement {
    89     private static final int ANNOTATION= 0x00002000;
    90     private static final int ENUM      = 0x00004000;
    91     private static final int SYNTHETIC = 0x00001000;
    92 
    93     /*
    94      * Constructor. Only the Java Virtual Machine creates Class
    95      * objects.
    96      */
    97     private Class() {}
    98 
    99 
   100     /**
   101      * Converts the object to a string. The string representation is the
   102      * string "class" or "interface", followed by a space, and then by the
   103      * fully qualified name of the class in the format returned by
   104      * {@code getName}.  If this {@code Class} object represents a
   105      * primitive type, this method returns the name of the primitive type.  If
   106      * this {@code Class} object represents void this method returns
   107      * "void".
   108      *
   109      * @return a string representation of this class object.
   110      */
   111     public String toString() {
   112         return (isInterface() ? "interface " : (isPrimitive() ? "" : "class "))
   113             + getName();
   114     }
   115 
   116 
   117     /**
   118      * Returns the {@code Class} object associated with the class or
   119      * interface with the given string name.  Invoking this method is
   120      * equivalent to:
   121      *
   122      * <blockquote>
   123      *  {@code Class.forName(className, true, currentLoader)}
   124      * </blockquote>
   125      *
   126      * where {@code currentLoader} denotes the defining class loader of
   127      * the current class.
   128      *
   129      * <p> For example, the following code fragment returns the
   130      * runtime {@code Class} descriptor for the class named
   131      * {@code java.lang.Thread}:
   132      *
   133      * <blockquote>
   134      *   {@code Class t = Class.forName("java.lang.Thread")}
   135      * </blockquote>
   136      * <p>
   137      * A call to {@code forName("X")} causes the class named
   138      * {@code X} to be initialized.
   139      *
   140      * @param      className   the fully qualified name of the desired class.
   141      * @return     the {@code Class} object for the class with the
   142      *             specified name.
   143      * @exception LinkageError if the linkage fails
   144      * @exception ExceptionInInitializerError if the initialization provoked
   145      *            by this method fails
   146      * @exception ClassNotFoundException if the class cannot be located
   147      */
   148     public static Class<?> forName(String className)
   149     throws ClassNotFoundException {
   150         if (className.startsWith("[")) {
   151             Class<?> arrType = defineArray(className);
   152             Class<?> c = arrType;
   153             while (c != null && c.isArray()) {
   154                 c = c.getComponentType0(); // verify component type is sane
   155             }
   156             return arrType;
   157         }
   158         Class<?> c = loadCls(className, className.replace('.', '_'));
   159         if (c == null) {
   160             throw new ClassNotFoundException(className);
   161         }
   162         return c;
   163     }
   164 
   165 
   166     /**
   167      * Returns the {@code Class} object associated with the class or
   168      * interface with the given string name, using the given class loader.
   169      * Given the fully qualified name for a class or interface (in the same
   170      * format returned by {@code getName}) this method attempts to
   171      * locate, load, and link the class or interface.  The specified class
   172      * loader is used to load the class or interface.  If the parameter
   173      * {@code loader} is null, the class is loaded through the bootstrap
   174      * class loader.  The class is initialized only if the
   175      * {@code initialize} parameter is {@code true} and if it has
   176      * not been initialized earlier.
   177      *
   178      * <p> If {@code name} denotes a primitive type or void, an attempt
   179      * will be made to locate a user-defined class in the unnamed package whose
   180      * name is {@code name}. Therefore, this method cannot be used to
   181      * obtain any of the {@code Class} objects representing primitive
   182      * types or void.
   183      *
   184      * <p> If {@code name} denotes an array class, the component type of
   185      * the array class is loaded but not initialized.
   186      *
   187      * <p> For example, in an instance method the expression:
   188      *
   189      * <blockquote>
   190      *  {@code Class.forName("Foo")}
   191      * </blockquote>
   192      *
   193      * is equivalent to:
   194      *
   195      * <blockquote>
   196      *  {@code Class.forName("Foo", true, this.getClass().getClassLoader())}
   197      * </blockquote>
   198      *
   199      * Note that this method throws errors related to loading, linking or
   200      * initializing as specified in Sections 12.2, 12.3 and 12.4 of <em>The
   201      * Java Language Specification</em>.
   202      * Note that this method does not check whether the requested class
   203      * is accessible to its caller.
   204      *
   205      * <p> If the {@code loader} is {@code null}, and a security
   206      * manager is present, and the caller's class loader is not null, then this
   207      * method calls the security manager's {@code checkPermission} method
   208      * with a {@code RuntimePermission("getClassLoader")} permission to
   209      * ensure it's ok to access the bootstrap class loader.
   210      *
   211      * @param name       fully qualified name of the desired class
   212      * @param initialize whether the class must be initialized
   213      * @param loader     class loader from which the class must be loaded
   214      * @return           class object representing the desired class
   215      *
   216      * @exception LinkageError if the linkage fails
   217      * @exception ExceptionInInitializerError if the initialization provoked
   218      *            by this method fails
   219      * @exception ClassNotFoundException if the class cannot be located by
   220      *            the specified class loader
   221      *
   222      * @see       java.lang.Class#forName(String)
   223      * @see       java.lang.ClassLoader
   224      * @since     1.2
   225      */
   226     public static Class<?> forName(String name, boolean initialize,
   227                                    ClassLoader loader)
   228         throws ClassNotFoundException
   229     {
   230         return forName(name);
   231     }
   232     
   233     @JavaScriptBody(args = {"n", "c" }, body =
   234         "if (vm[c]) return vm[c].$class;\n"
   235       + "if (vm.loadClass) {\n"
   236       + "  vm.loadClass(n);\n"
   237       + "  if (vm[c]) return vm[c].$class;\n"
   238       + "}\n"
   239       + "return null;"
   240     )
   241     private static native Class<?> loadCls(String n, String c);
   242 
   243 
   244     /**
   245      * Creates a new instance of the class represented by this {@code Class}
   246      * object.  The class is instantiated as if by a {@code new}
   247      * expression with an empty argument list.  The class is initialized if it
   248      * has not already been initialized.
   249      *
   250      * <p>Note that this method propagates any exception thrown by the
   251      * nullary constructor, including a checked exception.  Use of
   252      * this method effectively bypasses the compile-time exception
   253      * checking that would otherwise be performed by the compiler.
   254      * The {@link
   255      * java.lang.reflect.Constructor#newInstance(java.lang.Object...)
   256      * Constructor.newInstance} method avoids this problem by wrapping
   257      * any exception thrown by the constructor in a (checked) {@link
   258      * java.lang.reflect.InvocationTargetException}.
   259      *
   260      * @return     a newly allocated instance of the class represented by this
   261      *             object.
   262      * @exception  IllegalAccessException  if the class or its nullary
   263      *               constructor is not accessible.
   264      * @exception  InstantiationException
   265      *               if this {@code Class} represents an abstract class,
   266      *               an interface, an array class, a primitive type, or void;
   267      *               or if the class has no nullary constructor;
   268      *               or if the instantiation fails for some other reason.
   269      * @exception  ExceptionInInitializerError if the initialization
   270      *               provoked by this method fails.
   271      * @exception  SecurityException
   272      *             If a security manager, <i>s</i>, is present and any of the
   273      *             following conditions is met:
   274      *
   275      *             <ul>
   276      *
   277      *             <li> invocation of
   278      *             {@link SecurityManager#checkMemberAccess
   279      *             s.checkMemberAccess(this, Member.PUBLIC)} denies
   280      *             creation of new instances of this class
   281      *
   282      *             <li> the caller's class loader is not the same as or an
   283      *             ancestor of the class loader for the current class and
   284      *             invocation of {@link SecurityManager#checkPackageAccess
   285      *             s.checkPackageAccess()} denies access to the package
   286      *             of this class
   287      *
   288      *             </ul>
   289      *
   290      */
   291     @JavaScriptBody(args = { "self", "illegal" }, body =
   292           "\nvar c = self.cnstr;"
   293         + "\nif (c['cons__V']) {"
   294         + "\n  if ((c.cons__V.access & 0x1) != 0) {"
   295         + "\n    var inst = c();"
   296         + "\n    c.cons__V.call(inst);"
   297         + "\n    return inst;"
   298         + "\n  }"
   299         + "\n  return illegal;"
   300         + "\n}"
   301         + "\nreturn null;"
   302     )
   303     private static native Object newInstance0(Class<?> self, Object illegal);
   304     
   305     public T newInstance()
   306         throws InstantiationException, IllegalAccessException
   307     {
   308         Object illegal = new Object();
   309         Object inst = newInstance0(this, illegal);
   310         if (inst == null) {
   311             throw new InstantiationException(getName());
   312         }
   313         if (inst == illegal) {
   314             throw new IllegalAccessException();
   315         }
   316         return (T)inst;
   317     }
   318 
   319     /**
   320      * Determines if the specified {@code Object} is assignment-compatible
   321      * with the object represented by this {@code Class}.  This method is
   322      * the dynamic equivalent of the Java language {@code instanceof}
   323      * operator. The method returns {@code true} if the specified
   324      * {@code Object} argument is non-null and can be cast to the
   325      * reference type represented by this {@code Class} object without
   326      * raising a {@code ClassCastException.} It returns {@code false}
   327      * otherwise.
   328      *
   329      * <p> Specifically, if this {@code Class} object represents a
   330      * declared class, this method returns {@code true} if the specified
   331      * {@code Object} argument is an instance of the represented class (or
   332      * of any of its subclasses); it returns {@code false} otherwise. If
   333      * this {@code Class} object represents an array class, this method
   334      * returns {@code true} if the specified {@code Object} argument
   335      * can be converted to an object of the array class by an identity
   336      * conversion or by a widening reference conversion; it returns
   337      * {@code false} otherwise. If this {@code Class} object
   338      * represents an interface, this method returns {@code true} if the
   339      * class or any superclass of the specified {@code Object} argument
   340      * implements this interface; it returns {@code false} otherwise. If
   341      * this {@code Class} object represents a primitive type, this method
   342      * returns {@code false}.
   343      *
   344      * @param   obj the object to check
   345      * @return  true if {@code obj} is an instance of this class
   346      *
   347      * @since JDK1.1
   348      */
   349     public boolean isInstance(Object obj) {
   350         if (obj == null) {
   351             return false;
   352         }
   353         if (isArray()) {
   354             return isAssignableFrom(obj.getClass());
   355         }
   356         
   357         String prop = "$instOf_" + getName().replace('.', '_');
   358         return hasProperty(obj, prop);
   359     }
   360     
   361     @JavaScriptBody(args = { "who", "prop" }, body = 
   362         "if (who[prop]) return true; else return false;"
   363     )
   364     private static native boolean hasProperty(Object who, String prop);
   365 
   366 
   367     /**
   368      * Determines if the class or interface represented by this
   369      * {@code Class} object is either the same as, or is a superclass or
   370      * superinterface of, the class or interface represented by the specified
   371      * {@code Class} parameter. It returns {@code true} if so;
   372      * otherwise it returns {@code false}. If this {@code Class}
   373      * object represents a primitive type, this method returns
   374      * {@code true} if the specified {@code Class} parameter is
   375      * exactly this {@code Class} object; otherwise it returns
   376      * {@code false}.
   377      *
   378      * <p> Specifically, this method tests whether the type represented by the
   379      * specified {@code Class} parameter can be converted to the type
   380      * represented by this {@code Class} object via an identity conversion
   381      * or via a widening reference conversion. See <em>The Java Language
   382      * Specification</em>, sections 5.1.1 and 5.1.4 , for details.
   383      *
   384      * @param cls the {@code Class} object to be checked
   385      * @return the {@code boolean} value indicating whether objects of the
   386      * type {@code cls} can be assigned to objects of this class
   387      * @exception NullPointerException if the specified Class parameter is
   388      *            null.
   389      * @since JDK1.1
   390      */
   391     public boolean isAssignableFrom(Class<?> cls) {
   392         if (this == cls) {
   393             return true;
   394         }
   395         
   396         if (isArray()) {
   397             final Class<?> cmpType = cls.getComponentType();
   398             if (isPrimitive()) {
   399                 return this == cmpType;
   400             }
   401             return cmpType != null && getComponentType().isAssignableFrom(cmpType);
   402         }
   403         String prop = "$instOf_" + getName().replace('.', '_');
   404         return hasCnstrProperty(cls, prop);
   405     }
   406 
   407     @JavaScriptBody(args = { "who", "prop" }, body = 
   408         "if (who.cnstr.prototype[prop]) return true; else return false;"
   409     )
   410     private static native boolean hasCnstrProperty(Object who, String prop);
   411     
   412     
   413     /**
   414      * Determines if the specified {@code Class} object represents an
   415      * interface type.
   416      *
   417      * @return  {@code true} if this object represents an interface;
   418      *          {@code false} otherwise.
   419      */
   420     public boolean isInterface() {
   421         return (getAccess() & 0x200) != 0;
   422     }
   423     
   424     @JavaScriptBody(args = {}, body = "return this.access;")
   425     private native int getAccess();
   426 
   427 
   428     /**
   429      * Determines if this {@code Class} object represents an array class.
   430      *
   431      * @return  {@code true} if this object represents an array class;
   432      *          {@code false} otherwise.
   433      * @since   JDK1.1
   434      */
   435     public boolean isArray() {
   436         return hasProperty(this, "array"); // NOI18N
   437     }
   438 
   439 
   440     /**
   441      * Determines if the specified {@code Class} object represents a
   442      * primitive type.
   443      *
   444      * <p> There are nine predefined {@code Class} objects to represent
   445      * the eight primitive types and void.  These are created by the Java
   446      * Virtual Machine, and have the same names as the primitive types that
   447      * they represent, namely {@code boolean}, {@code byte},
   448      * {@code char}, {@code short}, {@code int},
   449      * {@code long}, {@code float}, and {@code double}.
   450      *
   451      * <p> These objects may only be accessed via the following public static
   452      * final variables, and are the only {@code Class} objects for which
   453      * this method returns {@code true}.
   454      *
   455      * @return true if and only if this class represents a primitive type
   456      *
   457      * @see     java.lang.Boolean#TYPE
   458      * @see     java.lang.Character#TYPE
   459      * @see     java.lang.Byte#TYPE
   460      * @see     java.lang.Short#TYPE
   461      * @see     java.lang.Integer#TYPE
   462      * @see     java.lang.Long#TYPE
   463      * @see     java.lang.Float#TYPE
   464      * @see     java.lang.Double#TYPE
   465      * @see     java.lang.Void#TYPE
   466      * @since JDK1.1
   467      */
   468     @JavaScriptBody(args = {}, body = 
   469            "if (this.primitive) return true;"
   470         + "else return false;"
   471     )
   472     public native boolean isPrimitive();
   473 
   474     /**
   475      * Returns true if this {@code Class} object represents an annotation
   476      * type.  Note that if this method returns true, {@link #isInterface()}
   477      * would also return true, as all annotation types are also interfaces.
   478      *
   479      * @return {@code true} if this class object represents an annotation
   480      *      type; {@code false} otherwise
   481      * @since 1.5
   482      */
   483     public boolean isAnnotation() {
   484         return (getModifiers() & ANNOTATION) != 0;
   485     }
   486 
   487     /**
   488      * Returns {@code true} if this class is a synthetic class;
   489      * returns {@code false} otherwise.
   490      * @return {@code true} if and only if this class is a synthetic class as
   491      *         defined by the Java Language Specification.
   492      * @since 1.5
   493      */
   494     public boolean isSynthetic() {
   495         return (getModifiers() & SYNTHETIC) != 0;
   496     }
   497 
   498     /**
   499      * Returns the  name of the entity (class, interface, array class,
   500      * primitive type, or void) represented by this {@code Class} object,
   501      * as a {@code String}.
   502      *
   503      * <p> If this class object represents a reference type that is not an
   504      * array type then the binary name of the class is returned, as specified
   505      * by
   506      * <cite>The Java&trade; Language Specification</cite>.
   507      *
   508      * <p> If this class object represents a primitive type or void, then the
   509      * name returned is a {@code String} equal to the Java language
   510      * keyword corresponding to the primitive type or void.
   511      *
   512      * <p> If this class object represents a class of arrays, then the internal
   513      * form of the name consists of the name of the element type preceded by
   514      * one or more '{@code [}' characters representing the depth of the array
   515      * nesting.  The encoding of element type names is as follows:
   516      *
   517      * <blockquote><table summary="Element types and encodings">
   518      * <tr><th> Element Type <th> &nbsp;&nbsp;&nbsp; <th> Encoding
   519      * <tr><td> boolean      <td> &nbsp;&nbsp;&nbsp; <td align=center> Z
   520      * <tr><td> byte         <td> &nbsp;&nbsp;&nbsp; <td align=center> B
   521      * <tr><td> char         <td> &nbsp;&nbsp;&nbsp; <td align=center> C
   522      * <tr><td> class or interface
   523      *                       <td> &nbsp;&nbsp;&nbsp; <td align=center> L<i>classname</i>;
   524      * <tr><td> double       <td> &nbsp;&nbsp;&nbsp; <td align=center> D
   525      * <tr><td> float        <td> &nbsp;&nbsp;&nbsp; <td align=center> F
   526      * <tr><td> int          <td> &nbsp;&nbsp;&nbsp; <td align=center> I
   527      * <tr><td> long         <td> &nbsp;&nbsp;&nbsp; <td align=center> J
   528      * <tr><td> short        <td> &nbsp;&nbsp;&nbsp; <td align=center> S
   529      * </table></blockquote>
   530      *
   531      * <p> The class or interface name <i>classname</i> is the binary name of
   532      * the class specified above.
   533      *
   534      * <p> Examples:
   535      * <blockquote><pre>
   536      * String.class.getName()
   537      *     returns "java.lang.String"
   538      * byte.class.getName()
   539      *     returns "byte"
   540      * (new Object[3]).getClass().getName()
   541      *     returns "[Ljava.lang.Object;"
   542      * (new int[3][4][5][6][7][8][9]).getClass().getName()
   543      *     returns "[[[[[[[I"
   544      * </pre></blockquote>
   545      *
   546      * @return  the name of the class or interface
   547      *          represented by this object.
   548      */
   549     public String getName() {
   550         return jvmName().replace('/', '.');
   551     }
   552 
   553     @JavaScriptBody(args = {}, body = "return this.jvmName;")
   554     private native String jvmName();
   555 
   556     
   557     /**
   558      * Returns an array of {@code TypeVariable} objects that represent the
   559      * type variables declared by the generic declaration represented by this
   560      * {@code GenericDeclaration} object, in declaration order.  Returns an
   561      * array of length 0 if the underlying generic declaration declares no type
   562      * variables.
   563      *
   564      * @return an array of {@code TypeVariable} objects that represent
   565      *     the type variables declared by this generic declaration
   566      * @throws java.lang.reflect.GenericSignatureFormatError if the generic
   567      *     signature of this generic declaration does not conform to
   568      *     the format specified in
   569      *     <cite>The Java&trade; Virtual Machine Specification</cite>
   570      * @since 1.5
   571      */
   572     public TypeVariable<Class<T>>[] getTypeParameters() {
   573         throw new UnsupportedOperationException();
   574     }
   575  
   576     /**
   577      * Returns the {@code Class} representing the superclass of the entity
   578      * (class, interface, primitive type or void) represented by this
   579      * {@code Class}.  If this {@code Class} represents either the
   580      * {@code Object} class, an interface, a primitive type, or void, then
   581      * null is returned.  If this object represents an array class then the
   582      * {@code Class} object representing the {@code Object} class is
   583      * returned.
   584      *
   585      * @return the superclass of the class represented by this object.
   586      */
   587     @JavaScriptBody(args = {}, body = "return this.superclass;")
   588     public native Class<? super T> getSuperclass();
   589 
   590     /**
   591      * Returns the Java language modifiers for this class or interface, encoded
   592      * in an integer. The modifiers consist of the Java Virtual Machine's
   593      * constants for {@code public}, {@code protected},
   594      * {@code private}, {@code final}, {@code static},
   595      * {@code abstract} and {@code interface}; they should be decoded
   596      * using the methods of class {@code Modifier}.
   597      *
   598      * <p> If the underlying class is an array class, then its
   599      * {@code public}, {@code private} and {@code protected}
   600      * modifiers are the same as those of its component type.  If this
   601      * {@code Class} represents a primitive type or void, its
   602      * {@code public} modifier is always {@code true}, and its
   603      * {@code protected} and {@code private} modifiers are always
   604      * {@code false}. If this object represents an array class, a
   605      * primitive type or void, then its {@code final} modifier is always
   606      * {@code true} and its interface modifier is always
   607      * {@code false}. The values of its other modifiers are not determined
   608      * by this specification.
   609      *
   610      * <p> The modifier encodings are defined in <em>The Java Virtual Machine
   611      * Specification</em>, table 4.1.
   612      *
   613      * @return the {@code int} representing the modifiers for this class
   614      * @see     java.lang.reflect.Modifier
   615      * @since JDK1.1
   616      */
   617     public int getModifiers() {
   618         return getAccess();
   619     }
   620 
   621 
   622     /**
   623      * Returns the simple name of the underlying class as given in the
   624      * source code. Returns an empty string if the underlying class is
   625      * anonymous.
   626      *
   627      * <p>The simple name of an array is the simple name of the
   628      * component type with "[]" appended.  In particular the simple
   629      * name of an array whose component type is anonymous is "[]".
   630      *
   631      * @return the simple name of the underlying class
   632      * @since 1.5
   633      */
   634     public String getSimpleName() {
   635         if (isArray())
   636             return getComponentType().getSimpleName()+"[]";
   637 
   638         String simpleName = getSimpleBinaryName();
   639         if (simpleName == null) { // top level class
   640             simpleName = getName();
   641             return simpleName.substring(simpleName.lastIndexOf(".")+1); // strip the package name
   642         }
   643         // According to JLS3 "Binary Compatibility" (13.1) the binary
   644         // name of non-package classes (not top level) is the binary
   645         // name of the immediately enclosing class followed by a '$' followed by:
   646         // (for nested and inner classes): the simple name.
   647         // (for local classes): 1 or more digits followed by the simple name.
   648         // (for anonymous classes): 1 or more digits.
   649 
   650         // Since getSimpleBinaryName() will strip the binary name of
   651         // the immediatly enclosing class, we are now looking at a
   652         // string that matches the regular expression "\$[0-9]*"
   653         // followed by a simple name (considering the simple of an
   654         // anonymous class to be the empty string).
   655 
   656         // Remove leading "\$[0-9]*" from the name
   657         int length = simpleName.length();
   658         if (length < 1 || simpleName.charAt(0) != '$')
   659             throw new IllegalStateException("Malformed class name");
   660         int index = 1;
   661         while (index < length && isAsciiDigit(simpleName.charAt(index)))
   662             index++;
   663         // Eventually, this is the empty string iff this is an anonymous class
   664         return simpleName.substring(index);
   665     }
   666 
   667     /**
   668      * Returns the "simple binary name" of the underlying class, i.e.,
   669      * the binary name without the leading enclosing class name.
   670      * Returns {@code null} if the underlying class is a top level
   671      * class.
   672      */
   673     private String getSimpleBinaryName() {
   674         Class<?> enclosingClass = null; // XXX getEnclosingClass();
   675         if (enclosingClass == null) // top level class
   676             return null;
   677         // Otherwise, strip the enclosing class' name
   678         try {
   679             return getName().substring(enclosingClass.getName().length());
   680         } catch (IndexOutOfBoundsException ex) {
   681             throw new IllegalStateException("Malformed class name");
   682         }
   683     }
   684 
   685     /**
   686      * Returns an array containing {@code Field} objects reflecting all
   687      * the accessible public fields of the class or interface represented by
   688      * this {@code Class} object.  The elements in the array returned are
   689      * not sorted and are not in any particular order.  This method returns an
   690      * array of length 0 if the class or interface has no accessible public
   691      * fields, or if it represents an array class, a primitive type, or void.
   692      *
   693      * <p> Specifically, if this {@code Class} object represents a class,
   694      * this method returns the public fields of this class and of all its
   695      * superclasses.  If this {@code Class} object represents an
   696      * interface, this method returns the fields of this interface and of all
   697      * its superinterfaces.
   698      *
   699      * <p> The implicit length field for array class is not reflected by this
   700      * method. User code should use the methods of class {@code Array} to
   701      * manipulate arrays.
   702      *
   703      * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.3.
   704      *
   705      * @return the array of {@code Field} objects representing the
   706      * public fields
   707      * @exception  SecurityException
   708      *             If a security manager, <i>s</i>, is present and any of the
   709      *             following conditions is met:
   710      *
   711      *             <ul>
   712      *
   713      *             <li> invocation of
   714      *             {@link SecurityManager#checkMemberAccess
   715      *             s.checkMemberAccess(this, Member.PUBLIC)} denies
   716      *             access to the fields within this class
   717      *
   718      *             <li> the caller's class loader is not the same as or an
   719      *             ancestor of the class loader for the current class and
   720      *             invocation of {@link SecurityManager#checkPackageAccess
   721      *             s.checkPackageAccess()} denies access to the package
   722      *             of this class
   723      *
   724      *             </ul>
   725      *
   726      * @since JDK1.1
   727      */
   728     public Field[] getFields() throws SecurityException {
   729         throw new SecurityException();
   730     }
   731 
   732     /**
   733      * Returns an array containing {@code Method} objects reflecting all
   734      * the public <em>member</em> methods of the class or interface represented
   735      * by this {@code Class} object, including those declared by the class
   736      * or interface and those inherited from superclasses and
   737      * superinterfaces.  Array classes return all the (public) member methods
   738      * inherited from the {@code Object} class.  The elements in the array
   739      * returned are not sorted and are not in any particular order.  This
   740      * method returns an array of length 0 if this {@code Class} object
   741      * represents a class or interface that has no public member methods, or if
   742      * this {@code Class} object represents a primitive type or void.
   743      *
   744      * <p> The class initialization method {@code <clinit>} is not
   745      * included in the returned array. If the class declares multiple public
   746      * member methods with the same parameter types, they are all included in
   747      * the returned array.
   748      *
   749      * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.4.
   750      *
   751      * @return the array of {@code Method} objects representing the
   752      * public methods of this class
   753      * @exception  SecurityException
   754      *             If a security manager, <i>s</i>, is present and any of the
   755      *             following conditions is met:
   756      *
   757      *             <ul>
   758      *
   759      *             <li> invocation of
   760      *             {@link SecurityManager#checkMemberAccess
   761      *             s.checkMemberAccess(this, Member.PUBLIC)} denies
   762      *             access to the methods within this class
   763      *
   764      *             <li> the caller's class loader is not the same as or an
   765      *             ancestor of the class loader for the current class and
   766      *             invocation of {@link SecurityManager#checkPackageAccess
   767      *             s.checkPackageAccess()} denies access to the package
   768      *             of this class
   769      *
   770      *             </ul>
   771      *
   772      * @since JDK1.1
   773      */
   774     public Method[] getMethods() throws SecurityException {
   775         return MethodImpl.findMethods(this, 0x01);
   776     }
   777 
   778     /**
   779      * Returns a {@code Field} object that reflects the specified public
   780      * member field of the class or interface represented by this
   781      * {@code Class} object. The {@code name} parameter is a
   782      * {@code String} specifying the simple name of the desired field.
   783      *
   784      * <p> The field to be reflected is determined by the algorithm that
   785      * follows.  Let C be the class represented by this object:
   786      * <OL>
   787      * <LI> If C declares a public field with the name specified, that is the
   788      *      field to be reflected.</LI>
   789      * <LI> If no field was found in step 1 above, this algorithm is applied
   790      *      recursively to each direct superinterface of C. The direct
   791      *      superinterfaces are searched in the order they were declared.</LI>
   792      * <LI> If no field was found in steps 1 and 2 above, and C has a
   793      *      superclass S, then this algorithm is invoked recursively upon S.
   794      *      If C has no superclass, then a {@code NoSuchFieldException}
   795      *      is thrown.</LI>
   796      * </OL>
   797      *
   798      * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.3.
   799      *
   800      * @param name the field name
   801      * @return  the {@code Field} object of this class specified by
   802      * {@code name}
   803      * @exception NoSuchFieldException if a field with the specified name is
   804      *              not found.
   805      * @exception NullPointerException if {@code name} is {@code null}
   806      * @exception  SecurityException
   807      *             If a security manager, <i>s</i>, is present and any of the
   808      *             following conditions is met:
   809      *
   810      *             <ul>
   811      *
   812      *             <li> invocation of
   813      *             {@link SecurityManager#checkMemberAccess
   814      *             s.checkMemberAccess(this, Member.PUBLIC)} denies
   815      *             access to the field
   816      *
   817      *             <li> the caller's class loader is not the same as or an
   818      *             ancestor of the class loader for the current class and
   819      *             invocation of {@link SecurityManager#checkPackageAccess
   820      *             s.checkPackageAccess()} denies access to the package
   821      *             of this class
   822      *
   823      *             </ul>
   824      *
   825      * @since JDK1.1
   826      */
   827     public Field getField(String name)
   828         throws SecurityException {
   829         throw new SecurityException();
   830     }
   831     
   832     
   833     /**
   834      * Returns a {@code Method} object that reflects the specified public
   835      * member method of the class or interface represented by this
   836      * {@code Class} object. The {@code name} parameter is a
   837      * {@code String} specifying the simple name of the desired method. The
   838      * {@code parameterTypes} parameter is an array of {@code Class}
   839      * objects that identify the method's formal parameter types, in declared
   840      * order. If {@code parameterTypes} is {@code null}, it is
   841      * treated as if it were an empty array.
   842      *
   843      * <p> If the {@code name} is "{@code <init>};"or "{@code <clinit>}" a
   844      * {@code NoSuchMethodException} is raised. Otherwise, the method to
   845      * be reflected is determined by the algorithm that follows.  Let C be the
   846      * class represented by this object:
   847      * <OL>
   848      * <LI> C is searched for any <I>matching methods</I>. If no matching
   849      *      method is found, the algorithm of step 1 is invoked recursively on
   850      *      the superclass of C.</LI>
   851      * <LI> If no method was found in step 1 above, the superinterfaces of C
   852      *      are searched for a matching method. If any such method is found, it
   853      *      is reflected.</LI>
   854      * </OL>
   855      *
   856      * To find a matching method in a class C:&nbsp; If C declares exactly one
   857      * public method with the specified name and exactly the same formal
   858      * parameter types, that is the method reflected. If more than one such
   859      * method is found in C, and one of these methods has a return type that is
   860      * more specific than any of the others, that method is reflected;
   861      * otherwise one of the methods is chosen arbitrarily.
   862      *
   863      * <p>Note that there may be more than one matching method in a
   864      * class because while the Java language forbids a class to
   865      * declare multiple methods with the same signature but different
   866      * return types, the Java virtual machine does not.  This
   867      * increased flexibility in the virtual machine can be used to
   868      * implement various language features.  For example, covariant
   869      * returns can be implemented with {@linkplain
   870      * java.lang.reflect.Method#isBridge bridge methods}; the bridge
   871      * method and the method being overridden would have the same
   872      * signature but different return types.
   873      *
   874      * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.4.
   875      *
   876      * @param name the name of the method
   877      * @param parameterTypes the list of parameters
   878      * @return the {@code Method} object that matches the specified
   879      * {@code name} and {@code parameterTypes}
   880      * @exception NoSuchMethodException if a matching method is not found
   881      *            or if the name is "&lt;init&gt;"or "&lt;clinit&gt;".
   882      * @exception NullPointerException if {@code name} is {@code null}
   883      * @exception  SecurityException
   884      *             If a security manager, <i>s</i>, is present and any of the
   885      *             following conditions is met:
   886      *
   887      *             <ul>
   888      *
   889      *             <li> invocation of
   890      *             {@link SecurityManager#checkMemberAccess
   891      *             s.checkMemberAccess(this, Member.PUBLIC)} denies
   892      *             access to the method
   893      *
   894      *             <li> the caller's class loader is not the same as or an
   895      *             ancestor of the class loader for the current class and
   896      *             invocation of {@link SecurityManager#checkPackageAccess
   897      *             s.checkPackageAccess()} denies access to the package
   898      *             of this class
   899      *
   900      *             </ul>
   901      *
   902      * @since JDK1.1
   903      */
   904     public Method getMethod(String name, Class<?>... parameterTypes)
   905         throws SecurityException, NoSuchMethodException {
   906         Method m = MethodImpl.findMethod(this, name, parameterTypes);
   907         if (m == null) {
   908             StringBuilder sb = new StringBuilder();
   909             sb.append(getName()).append('.').append(name).append('(');
   910             String sep = "";
   911             for (int i = 0; i < parameterTypes.length; i++) {
   912                 sb.append(sep).append(parameterTypes[i].getName());
   913                 sep = ", ";
   914             }
   915             sb.append(')');
   916             throw new NoSuchMethodException(sb.toString());
   917         }
   918         return m;
   919     }
   920     
   921     /**
   922      * Returns an array of {@code Method} objects reflecting all the
   923      * methods declared by the class or interface represented by this
   924      * {@code Class} object. This includes public, protected, default
   925      * (package) access, and private methods, but excludes inherited methods.
   926      * The elements in the array returned are not sorted and are not in any
   927      * particular order.  This method returns an array of length 0 if the class
   928      * or interface declares no methods, or if this {@code Class} object
   929      * represents a primitive type, an array class, or void.  The class
   930      * initialization method {@code <clinit>} is not included in the
   931      * returned array. If the class declares multiple public member methods
   932      * with the same parameter types, they are all included in the returned
   933      * array.
   934      *
   935      * <p> See <em>The Java Language Specification</em>, section 8.2.
   936      *
   937      * @return    the array of {@code Method} objects representing all the
   938      * declared methods of this class
   939      * @exception  SecurityException
   940      *             If a security manager, <i>s</i>, is present and any of the
   941      *             following conditions is met:
   942      *
   943      *             <ul>
   944      *
   945      *             <li> invocation of
   946      *             {@link SecurityManager#checkMemberAccess
   947      *             s.checkMemberAccess(this, Member.DECLARED)} denies
   948      *             access to the declared methods within this class
   949      *
   950      *             <li> the caller's class loader is not the same as or an
   951      *             ancestor of the class loader for the current class and
   952      *             invocation of {@link SecurityManager#checkPackageAccess
   953      *             s.checkPackageAccess()} denies access to the package
   954      *             of this class
   955      *
   956      *             </ul>
   957      *
   958      * @since JDK1.1
   959      */
   960     public Method[] getDeclaredMethods() throws SecurityException {
   961         throw new SecurityException();
   962     }
   963     
   964     /**
   965      * Character.isDigit answers {@code true} to some non-ascii
   966      * digits.  This one does not.
   967      */
   968     private static boolean isAsciiDigit(char c) {
   969         return '0' <= c && c <= '9';
   970     }
   971 
   972     /**
   973      * Returns the canonical name of the underlying class as
   974      * defined by the Java Language Specification.  Returns null if
   975      * the underlying class does not have a canonical name (i.e., if
   976      * it is a local or anonymous class or an array whose component
   977      * type does not have a canonical name).
   978      * @return the canonical name of the underlying class if it exists, and
   979      * {@code null} otherwise.
   980      * @since 1.5
   981      */
   982     public String getCanonicalName() {
   983         if (isArray()) {
   984             String canonicalName = getComponentType().getCanonicalName();
   985             if (canonicalName != null)
   986                 return canonicalName + "[]";
   987             else
   988                 return null;
   989         }
   990 //        if (isLocalOrAnonymousClass())
   991 //            return null;
   992 //        Class<?> enclosingClass = getEnclosingClass();
   993         Class<?> enclosingClass = null;
   994         if (enclosingClass == null) { // top level class
   995             return getName();
   996         } else {
   997             String enclosingName = enclosingClass.getCanonicalName();
   998             if (enclosingName == null)
   999                 return null;
  1000             return enclosingName + "." + getSimpleName();
  1001         }
  1002     }
  1003 
  1004     /**
  1005      * Finds a resource with a given name.  The rules for searching resources
  1006      * associated with a given class are implemented by the defining
  1007      * {@linkplain ClassLoader class loader} of the class.  This method
  1008      * delegates to this object's class loader.  If this object was loaded by
  1009      * the bootstrap class loader, the method delegates to {@link
  1010      * ClassLoader#getSystemResourceAsStream}.
  1011      *
  1012      * <p> Before delegation, an absolute resource name is constructed from the
  1013      * given resource name using this algorithm:
  1014      *
  1015      * <ul>
  1016      *
  1017      * <li> If the {@code name} begins with a {@code '/'}
  1018      * (<tt>'&#92;u002f'</tt>), then the absolute name of the resource is the
  1019      * portion of the {@code name} following the {@code '/'}.
  1020      *
  1021      * <li> Otherwise, the absolute name is of the following form:
  1022      *
  1023      * <blockquote>
  1024      *   {@code modified_package_name/name}
  1025      * </blockquote>
  1026      *
  1027      * <p> Where the {@code modified_package_name} is the package name of this
  1028      * object with {@code '/'} substituted for {@code '.'}
  1029      * (<tt>'&#92;u002e'</tt>).
  1030      *
  1031      * </ul>
  1032      *
  1033      * @param  name name of the desired resource
  1034      * @return      A {@link java.io.InputStream} object or {@code null} if
  1035      *              no resource with this name is found
  1036      * @throws  NullPointerException If {@code name} is {@code null}
  1037      * @since  JDK1.1
  1038      */
  1039      public InputStream getResourceAsStream(String name) {
  1040         name = resolveName(name);
  1041         byte[] arr = getResourceAsStream0(name);
  1042         return arr == null ? null : new ByteArrayInputStream(arr);
  1043      }
  1044      
  1045      @JavaScriptBody(args = "name", body = 
  1046          "return (vm.loadBytes) ? vm.loadBytes(name) : null;"
  1047      )
  1048      private static native byte[] getResourceAsStream0(String name);
  1049 
  1050     /**
  1051      * Finds a resource with a given name.  The rules for searching resources
  1052      * associated with a given class are implemented by the defining
  1053      * {@linkplain ClassLoader class loader} of the class.  This method
  1054      * delegates to this object's class loader.  If this object was loaded by
  1055      * the bootstrap class loader, the method delegates to {@link
  1056      * ClassLoader#getSystemResource}.
  1057      *
  1058      * <p> Before delegation, an absolute resource name is constructed from the
  1059      * given resource name using this algorithm:
  1060      *
  1061      * <ul>
  1062      *
  1063      * <li> If the {@code name} begins with a {@code '/'}
  1064      * (<tt>'&#92;u002f'</tt>), then the absolute name of the resource is the
  1065      * portion of the {@code name} following the {@code '/'}.
  1066      *
  1067      * <li> Otherwise, the absolute name is of the following form:
  1068      *
  1069      * <blockquote>
  1070      *   {@code modified_package_name/name}
  1071      * </blockquote>
  1072      *
  1073      * <p> Where the {@code modified_package_name} is the package name of this
  1074      * object with {@code '/'} substituted for {@code '.'}
  1075      * (<tt>'&#92;u002e'</tt>).
  1076      *
  1077      * </ul>
  1078      *
  1079      * @param  name name of the desired resource
  1080      * @return      A  {@link java.net.URL} object or {@code null} if no
  1081      *              resource with this name is found
  1082      * @since  JDK1.1
  1083      */
  1084     public java.net.URL getResource(String name) {
  1085         InputStream is = getResourceAsStream(name);
  1086         return is == null ? null : newResourceURL(URL.class, "res:/" + name, is);
  1087     }
  1088     
  1089     @JavaScriptBody(args = { "url", "spec", "is" }, body = 
  1090         "var u = url.cnstr(true);\n"
  1091       + "u.constructor.cons__VLjava_lang_String_2Ljava_io_InputStream_2.call(u, spec, is);\n"
  1092       + "return u;"
  1093     )
  1094     private static native URL newResourceURL(Class<URL> url, String spec, InputStream is);
  1095 
  1096    /**
  1097      * Add a package name prefix if the name is not absolute Remove leading "/"
  1098      * if name is absolute
  1099      */
  1100     private String resolveName(String name) {
  1101         if (name == null) {
  1102             return name;
  1103         }
  1104         if (!name.startsWith("/")) {
  1105             Class<?> c = this;
  1106             while (c.isArray()) {
  1107                 c = c.getComponentType();
  1108             }
  1109             String baseName = c.getName();
  1110             int index = baseName.lastIndexOf('.');
  1111             if (index != -1) {
  1112                 name = baseName.substring(0, index).replace('.', '/')
  1113                     +"/"+name;
  1114             }
  1115         } else {
  1116             name = name.substring(1);
  1117         }
  1118         return name;
  1119     }
  1120     
  1121     /**
  1122      * Returns the class loader for the class.  Some implementations may use
  1123      * null to represent the bootstrap class loader. This method will return
  1124      * null in such implementations if this class was loaded by the bootstrap
  1125      * class loader.
  1126      *
  1127      * <p> If a security manager is present, and the caller's class loader is
  1128      * not null and the caller's class loader is not the same as or an ancestor of
  1129      * the class loader for the class whose class loader is requested, then
  1130      * this method calls the security manager's {@code checkPermission}
  1131      * method with a {@code RuntimePermission("getClassLoader")}
  1132      * permission to ensure it's ok to access the class loader for the class.
  1133      *
  1134      * <p>If this object
  1135      * represents a primitive type or void, null is returned.
  1136      *
  1137      * @return  the class loader that loaded the class or interface
  1138      *          represented by this object.
  1139      * @throws SecurityException
  1140      *    if a security manager exists and its
  1141      *    {@code checkPermission} method denies
  1142      *    access to the class loader for the class.
  1143      * @see java.lang.ClassLoader
  1144      * @see SecurityManager#checkPermission
  1145      * @see java.lang.RuntimePermission
  1146      */
  1147     public ClassLoader getClassLoader() {
  1148         throw new SecurityException();
  1149     }
  1150 
  1151     /**
  1152      * Determines the interfaces implemented by the class or interface
  1153      * represented by this object.
  1154      *
  1155      * <p> If this object represents a class, the return value is an array
  1156      * containing objects representing all interfaces implemented by the
  1157      * class. The order of the interface objects in the array corresponds to
  1158      * the order of the interface names in the {@code implements} clause
  1159      * of the declaration of the class represented by this object. For
  1160      * example, given the declaration:
  1161      * <blockquote>
  1162      * {@code class Shimmer implements FloorWax, DessertTopping { ... }}
  1163      * </blockquote>
  1164      * suppose the value of {@code s} is an instance of
  1165      * {@code Shimmer}; the value of the expression:
  1166      * <blockquote>
  1167      * {@code s.getClass().getInterfaces()[0]}
  1168      * </blockquote>
  1169      * is the {@code Class} object that represents interface
  1170      * {@code FloorWax}; and the value of:
  1171      * <blockquote>
  1172      * {@code s.getClass().getInterfaces()[1]}
  1173      * </blockquote>
  1174      * is the {@code Class} object that represents interface
  1175      * {@code DessertTopping}.
  1176      *
  1177      * <p> If this object represents an interface, the array contains objects
  1178      * representing all interfaces extended by the interface. The order of the
  1179      * interface objects in the array corresponds to the order of the interface
  1180      * names in the {@code extends} clause of the declaration of the
  1181      * interface represented by this object.
  1182      *
  1183      * <p> If this object represents a class or interface that implements no
  1184      * interfaces, the method returns an array of length 0.
  1185      *
  1186      * <p> If this object represents a primitive type or void, the method
  1187      * returns an array of length 0.
  1188      *
  1189      * @return an array of interfaces implemented by this class.
  1190      */
  1191     public native Class<?>[] getInterfaces();
  1192     
  1193     /**
  1194      * Returns the {@code Class} representing the component type of an
  1195      * array.  If this class does not represent an array class this method
  1196      * returns null.
  1197      *
  1198      * @return the {@code Class} representing the component type of this
  1199      * class if this class is an array
  1200      * @see     java.lang.reflect.Array
  1201      * @since JDK1.1
  1202      */
  1203     public Class<?> getComponentType() {
  1204         if (isArray()) {
  1205             try {
  1206                 return getComponentType0();
  1207             } catch (ClassNotFoundException cnfe) {
  1208                 throw new IllegalStateException(cnfe);
  1209             }
  1210         }
  1211         return null;
  1212     }
  1213 
  1214     private Class<?> getComponentType0() throws ClassNotFoundException {
  1215         String n = getName().substring(1);
  1216         switch (n.charAt(0)) {
  1217             case 'L': 
  1218                 n = n.substring(1, n.length() - 1);
  1219                 return Class.forName(n);
  1220             case 'I':
  1221                 return Integer.TYPE;
  1222             case 'J':
  1223                 return Long.TYPE;
  1224             case 'D':
  1225                 return Double.TYPE;
  1226             case 'F':
  1227                 return Float.TYPE;
  1228             case 'B':
  1229                 return Byte.TYPE;
  1230             case 'Z':
  1231                 return Boolean.TYPE;
  1232             case 'S':
  1233                 return Short.TYPE;
  1234             case 'V':
  1235                 return Void.TYPE;
  1236             case 'C':
  1237                 return Character.TYPE;
  1238             case '[':
  1239                 return defineArray(n);
  1240             default:
  1241                 throw new ClassNotFoundException("Unknown component type of " + getName());
  1242         }
  1243     }
  1244     
  1245     @JavaScriptBody(args = { "sig" }, body = 
  1246         "var c = Array[sig];\n" +
  1247         "if (c) return c;\n" +
  1248         "c = vm.java_lang_Class(true);\n" +
  1249         "c.jvmName = sig;\n" +
  1250         "c.superclass = vm.java_lang_Object(false).$class;\n" +
  1251         "c.array = true;\n" +
  1252         "Array[sig] = c;\n" +
  1253         "return c;"
  1254     )
  1255     private static native Class<?> defineArray(String sig);
  1256     
  1257     /**
  1258      * Returns true if and only if this class was declared as an enum in the
  1259      * source code.
  1260      *
  1261      * @return true if and only if this class was declared as an enum in the
  1262      *     source code
  1263      * @since 1.5
  1264      */
  1265     public boolean isEnum() {
  1266         // An enum must both directly extend java.lang.Enum and have
  1267         // the ENUM bit set; classes for specialized enum constants
  1268         // don't do the former.
  1269         return (this.getModifiers() & ENUM) != 0 &&
  1270         this.getSuperclass() == java.lang.Enum.class;
  1271     }
  1272 
  1273     /**
  1274      * Casts an object to the class or interface represented
  1275      * by this {@code Class} object.
  1276      *
  1277      * @param obj the object to be cast
  1278      * @return the object after casting, or null if obj is null
  1279      *
  1280      * @throws ClassCastException if the object is not
  1281      * null and is not assignable to the type T.
  1282      *
  1283      * @since 1.5
  1284      */
  1285     public T cast(Object obj) {
  1286         if (obj != null && !isInstance(obj))
  1287             throw new ClassCastException(cannotCastMsg(obj));
  1288         return (T) obj;
  1289     }
  1290 
  1291     private String cannotCastMsg(Object obj) {
  1292         return "Cannot cast " + obj.getClass().getName() + " to " + getName();
  1293     }
  1294 
  1295     /**
  1296      * Casts this {@code Class} object to represent a subclass of the class
  1297      * represented by the specified class object.  Checks that that the cast
  1298      * is valid, and throws a {@code ClassCastException} if it is not.  If
  1299      * this method succeeds, it always returns a reference to this class object.
  1300      *
  1301      * <p>This method is useful when a client needs to "narrow" the type of
  1302      * a {@code Class} object to pass it to an API that restricts the
  1303      * {@code Class} objects that it is willing to accept.  A cast would
  1304      * generate a compile-time warning, as the correctness of the cast
  1305      * could not be checked at runtime (because generic types are implemented
  1306      * by erasure).
  1307      *
  1308      * @return this {@code Class} object, cast to represent a subclass of
  1309      *    the specified class object.
  1310      * @throws ClassCastException if this {@code Class} object does not
  1311      *    represent a subclass of the specified class (here "subclass" includes
  1312      *    the class itself).
  1313      * @since 1.5
  1314      */
  1315     public <U> Class<? extends U> asSubclass(Class<U> clazz) {
  1316         if (clazz.isAssignableFrom(this))
  1317             return (Class<? extends U>) this;
  1318         else
  1319             throw new ClassCastException(this.toString());
  1320     }
  1321 
  1322     @JavaScriptBody(args = { "ac" }, 
  1323         body = 
  1324           "if (this.anno) {"
  1325         + "  return this.anno['L' + ac.jvmName + ';'];"
  1326         + "} else return null;"
  1327     )
  1328     private Object getAnnotationData(Class<?> annotationClass) {
  1329         throw new UnsupportedOperationException();
  1330     }
  1331     /**
  1332      * @throws NullPointerException {@inheritDoc}
  1333      * @since 1.5
  1334      */
  1335     public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {
  1336         Object data = getAnnotationData(annotationClass);
  1337         return data == null ? null : AnnotationImpl.create(annotationClass, data);
  1338     }
  1339 
  1340     /**
  1341      * @throws NullPointerException {@inheritDoc}
  1342      * @since 1.5
  1343      */
  1344     @JavaScriptBody(args = { "ac" }, 
  1345         body = "if (this.anno && this.anno['L' + ac.jvmName + ';']) { return true; }"
  1346         + "else return false;"
  1347     )
  1348     public boolean isAnnotationPresent(
  1349         Class<? extends Annotation> annotationClass) {
  1350         if (annotationClass == null)
  1351             throw new NullPointerException();
  1352 
  1353         return getAnnotation(annotationClass) != null;
  1354     }
  1355 
  1356     @JavaScriptBody(args = {}, body = "return this.anno;")
  1357     private Object getAnnotationData() {
  1358         throw new UnsupportedOperationException();
  1359     }
  1360 
  1361     /**
  1362      * @since 1.5
  1363      */
  1364     public Annotation[] getAnnotations() {
  1365         Object data = getAnnotationData();
  1366         return data == null ? new Annotation[0] : AnnotationImpl.create(data);
  1367     }
  1368 
  1369     /**
  1370      * @since 1.5
  1371      */
  1372     public Annotation[] getDeclaredAnnotations()  {
  1373         throw new UnsupportedOperationException();
  1374     }
  1375 
  1376     @JavaScriptBody(args = "type", body = ""
  1377         + "var c = vm.java_lang_Class(true);"
  1378         + "c.jvmName = type;"
  1379         + "c.primitive = true;"
  1380         + "return c;"
  1381     )
  1382     native static Class getPrimitiveClass(String type);
  1383 
  1384     @JavaScriptBody(args = {}, body = 
  1385         "return vm.desiredAssertionStatus ? vm.desiredAssertionStatus : false;"
  1386     )
  1387     public native boolean desiredAssertionStatus();
  1388 }