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