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