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