rt/emul/mini/src/main/java/java/lang/Class.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Thu, 22 May 2014 12:19:52 +0200
branchclosure
changeset 1585 60dcb3d7a687
parent 1532 10d26626c426
child 1586 d4ee65642d8d
permissions -rw-r--r--
Seek the class in VM as well as among exported symbols to allow calculator demo to start in full obfuscation mode
     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 java.io.InputStream;
    30 import java.lang.annotation.Annotation;
    31 import java.lang.reflect.Array;
    32 import java.lang.reflect.Constructor;
    33 import java.lang.reflect.Field;
    34 import java.lang.reflect.Method;
    35 import java.lang.reflect.TypeVariable;
    36 import java.net.URL;
    37 import org.apidesign.bck2brwsr.core.JavaScriptBody;
    38 import org.apidesign.bck2brwsr.core.JavaScriptOnly;
    39 import org.apidesign.bck2brwsr.emul.reflect.AnnotationImpl;
    40 import org.apidesign.bck2brwsr.emul.reflect.MethodImpl;
    41 
    42 /**
    43  * Instances of the class {@code Class} represent classes and
    44  * interfaces in a running Java application.  An enum is a kind of
    45  * class and an annotation is a kind of interface.  Every array also
    46  * belongs to a class that is reflected as a {@code Class} object
    47  * that is shared by all arrays with the same element type and number
    48  * of dimensions.  The primitive Java types ({@code boolean},
    49  * {@code byte}, {@code char}, {@code short},
    50  * {@code int}, {@code long}, {@code float}, and
    51  * {@code double}), and the keyword {@code void} are also
    52  * represented as {@code Class} objects.
    53  *
    54  * <p> {@code Class} has no public constructor. Instead {@code Class}
    55  * objects are constructed automatically by the Java Virtual Machine as classes
    56  * are loaded and by calls to the {@code defineClass} method in the class
    57  * loader.
    58  *
    59  * <p> The following example uses a {@code Class} object to print the
    60  * class name of an object:
    61  *
    62  * <p> <blockquote><pre>
    63  *     void printClassName(Object obj) {
    64  *         System.out.println("The class of " + obj +
    65  *                            " is " + obj.getClass().getName());
    66  *     }
    67  * </pre></blockquote>
    68  *
    69  * <p> It is also possible to get the {@code Class} object for a named
    70  * type (or for void) using a class literal.  See Section 15.8.2 of
    71  * <cite>The Java&trade; Language Specification</cite>.
    72  * For example:
    73  *
    74  * <p> <blockquote>
    75  *     {@code System.out.println("The name of class Foo is: "+Foo.class.getName());}
    76  * </blockquote>
    77  *
    78  * @param <T> the type of the class modeled by this {@code Class}
    79  * object.  For example, the type of {@code String.class} is {@code
    80  * Class<String>}.  Use {@code Class<?>} if the class being modeled is
    81  * unknown.
    82  *
    83  * @author  unascribed
    84  * @see     java.lang.ClassLoader#defineClass(byte[], int, int)
    85  * @since   JDK1.0
    86  */
    87 public final
    88     class Class<T> implements java.io.Serializable,
    89                               java.lang.reflect.GenericDeclaration,
    90                               java.lang.reflect.Type,
    91                               java.lang.reflect.AnnotatedElement {
    92     private static final int ANNOTATION= 0x00002000;
    93     private static final int ENUM      = 0x00004000;
    94     private static final int SYNTHETIC = 0x00001000;
    95 
    96     /*
    97      * Constructor. Only the Java Virtual Machine creates Class
    98      * objects.
    99      */
   100     private Class() {}
   101 
   102 
   103     /**
   104      * Converts the object to a string. The string representation is the
   105      * string "class" or "interface", followed by a space, and then by the
   106      * fully qualified name of the class in the format returned by
   107      * {@code getName}.  If this {@code Class} object represents a
   108      * primitive type, this method returns the name of the primitive type.  If
   109      * this {@code Class} object represents void this method returns
   110      * "void".
   111      *
   112      * @return a string representation of this class object.
   113      */
   114     public String toString() {
   115         return (isInterface() ? "interface " : (isPrimitive() ? "" : "class "))
   116             + getName();
   117     }
   118 
   119 
   120     /**
   121      * Returns the {@code Class} object associated with the class or
   122      * interface with the given string name.  Invoking this method is
   123      * equivalent to:
   124      *
   125      * <blockquote>
   126      *  {@code Class.forName(className, true, currentLoader)}
   127      * </blockquote>
   128      *
   129      * where {@code currentLoader} denotes the defining class loader of
   130      * the current class.
   131      *
   132      * <p> For example, the following code fragment returns the
   133      * runtime {@code Class} descriptor for the class named
   134      * {@code java.lang.Thread}:
   135      *
   136      * <blockquote>
   137      *   {@code Class t = Class.forName("java.lang.Thread")}
   138      * </blockquote>
   139      * <p>
   140      * A call to {@code forName("X")} causes the class named
   141      * {@code X} to be initialized.
   142      *
   143      * @param      className   the fully qualified name of the desired class.
   144      * @return     the {@code Class} object for the class with the
   145      *             specified name.
   146      * @exception LinkageError if the linkage fails
   147      * @exception ExceptionInInitializerError if the initialization provoked
   148      *            by this method fails
   149      * @exception ClassNotFoundException if the class cannot be located
   150      */
   151     public static Class<?> forName(String className)
   152     throws ClassNotFoundException {
   153         if (className.startsWith("[")) {
   154             Class<?> arrType = defineArray(className, null);
   155             Class<?> c = arrType;
   156             while (c != null && c.isArray()) {
   157                 c = c.getComponentType0(); // verify component type is sane
   158             }
   159             return arrType;
   160         }
   161         try {
   162             Class<?> c = loadCls(className, className.replace('.', '_'));
   163             if (c == null) {
   164                 throw new ClassNotFoundException(className);
   165             }
   166             return c;
   167         } catch (Throwable ex) {
   168             throw new ClassNotFoundException(className, ex);
   169         }
   170     }
   171 
   172 
   173     /**
   174      * Returns the {@code Class} object associated with the class or
   175      * interface with the given string name, using the given class loader.
   176      * Given the fully qualified name for a class or interface (in the same
   177      * format returned by {@code getName}) this method attempts to
   178      * locate, load, and link the class or interface.  The specified class
   179      * loader is used to load the class or interface.  If the parameter
   180      * {@code loader} is null, the class is loaded through the bootstrap
   181      * class loader.  The class is initialized only if the
   182      * {@code initialize} parameter is {@code true} and if it has
   183      * not been initialized earlier.
   184      *
   185      * <p> If {@code name} denotes a primitive type or void, an attempt
   186      * will be made to locate a user-defined class in the unnamed package whose
   187      * name is {@code name}. Therefore, this method cannot be used to
   188      * obtain any of the {@code Class} objects representing primitive
   189      * types or void.
   190      *
   191      * <p> If {@code name} denotes an array class, the component type of
   192      * the array class is loaded but not initialized.
   193      *
   194      * <p> For example, in an instance method the expression:
   195      *
   196      * <blockquote>
   197      *  {@code Class.forName("Foo")}
   198      * </blockquote>
   199      *
   200      * is equivalent to:
   201      *
   202      * <blockquote>
   203      *  {@code Class.forName("Foo", true, this.getClass().getClassLoader())}
   204      * </blockquote>
   205      *
   206      * Note that this method throws errors related to loading, linking or
   207      * initializing as specified in Sections 12.2, 12.3 and 12.4 of <em>The
   208      * Java Language Specification</em>.
   209      * Note that this method does not check whether the requested class
   210      * is accessible to its caller.
   211      *
   212      * <p> If the {@code loader} is {@code null}, and a security
   213      * manager is present, and the caller's class loader is not null, then this
   214      * method calls the security manager's {@code checkPermission} method
   215      * with a {@code RuntimePermission("getClassLoader")} permission to
   216      * ensure it's ok to access the bootstrap class loader.
   217      *
   218      * @param name       fully qualified name of the desired class
   219      * @param initialize whether the class must be initialized
   220      * @param loader     class loader from which the class must be loaded
   221      * @return           class object representing the desired class
   222      *
   223      * @exception LinkageError if the linkage fails
   224      * @exception ExceptionInInitializerError if the initialization provoked
   225      *            by this method fails
   226      * @exception ClassNotFoundException if the class cannot be located by
   227      *            the specified class loader
   228      *
   229      * @see       java.lang.Class#forName(String)
   230      * @see       java.lang.ClassLoader
   231      * @since     1.2
   232      */
   233     public static Class<?> forName(String name, boolean initialize,
   234                                    ClassLoader loader)
   235         throws ClassNotFoundException
   236     {
   237         return forName(name);
   238     }
   239     
   240     @JavaScriptBody(args = {"n", "c" }, body =
   241         "var m = vm[c];\n"
   242       + "if (!m) {\n"
   243       + "  var l = vm.loadClass ? vm.loadClass : exports ? exports.loadClass : null;\n"
   244       + "  if (l) {\n"
   245       + "    l(n);\n"
   246       + "  }\n"
   247       + "  if (vm[c]) m = vm[c];\n"
   248       + "  else if (exports[c]) m = exports[c];\n"
   249       + "}\n"
   250       + "if (!m) return null;"
   251       + "m(false);"
   252       + "return m.$class;"
   253     )
   254     private static native Class<?> loadCls(String n, String c);
   255 
   256 
   257     /**
   258      * Creates a new instance of the class represented by this {@code Class}
   259      * object.  The class is instantiated as if by a {@code new}
   260      * expression with an empty argument list.  The class is initialized if it
   261      * has not already been initialized.
   262      *
   263      * <p>Note that this method propagates any exception thrown by the
   264      * nullary constructor, including a checked exception.  Use of
   265      * this method effectively bypasses the compile-time exception
   266      * checking that would otherwise be performed by the compiler.
   267      * The {@link
   268      * java.lang.reflect.Constructor#newInstance(java.lang.Object...)
   269      * Constructor.newInstance} method avoids this problem by wrapping
   270      * any exception thrown by the constructor in a (checked) {@link
   271      * java.lang.reflect.InvocationTargetException}.
   272      *
   273      * @return     a newly allocated instance of the class represented by this
   274      *             object.
   275      * @exception  IllegalAccessException  if the class or its nullary
   276      *               constructor is not accessible.
   277      * @exception  InstantiationException
   278      *               if this {@code Class} represents an abstract class,
   279      *               an interface, an array class, a primitive type, or void;
   280      *               or if the class has no nullary constructor;
   281      *               or if the instantiation fails for some other reason.
   282      * @exception  ExceptionInInitializerError if the initialization
   283      *               provoked by this method fails.
   284      * @exception  SecurityException
   285      *             If a security manager, <i>s</i>, is present and any of the
   286      *             following conditions is met:
   287      *
   288      *             <ul>
   289      *
   290      *             <li> invocation of
   291      *             {@link SecurityManager#checkMemberAccess
   292      *             s.checkMemberAccess(this, Member.PUBLIC)} denies
   293      *             creation of new instances of this class
   294      *
   295      *             <li> the caller's class loader is not the same as or an
   296      *             ancestor of the class loader for the current class and
   297      *             invocation of {@link SecurityManager#checkPackageAccess
   298      *             s.checkPackageAccess()} denies access to the package
   299      *             of this class
   300      *
   301      *             </ul>
   302      *
   303      */
   304     @JavaScriptBody(args = { "self", "illegal" }, body =
   305           "\nvar c = self.cnstr;"
   306         + "\nif (c['cons__V']) {"
   307         + "\n  if ((c.cons__V.access & 0x1) != 0) {"
   308         + "\n    var inst = c();"
   309         + "\n    c.cons__V.call(inst);"
   310         + "\n    return inst;"
   311         + "\n  }"
   312         + "\n  return illegal;"
   313         + "\n}"
   314         + "\nreturn null;"
   315     )
   316     private static native Object newInstance0(Class<?> self, Object illegal);
   317     
   318     public T newInstance()
   319         throws InstantiationException, IllegalAccessException
   320     {
   321         Object illegal = new Object();
   322         Object inst = newInstance0(this, illegal);
   323         if (inst == null) {
   324             throw new InstantiationException(getName());
   325         }
   326         if (inst == illegal) {
   327             throw new IllegalAccessException();
   328         }
   329         return (T)inst;
   330     }
   331 
   332     /**
   333      * Determines if the specified {@code Object} is assignment-compatible
   334      * with the object represented by this {@code Class}.  This method is
   335      * the dynamic equivalent of the Java language {@code instanceof}
   336      * operator. The method returns {@code true} if the specified
   337      * {@code Object} argument is non-null and can be cast to the
   338      * reference type represented by this {@code Class} object without
   339      * raising a {@code ClassCastException.} It returns {@code false}
   340      * otherwise.
   341      *
   342      * <p> Specifically, if this {@code Class} object represents a
   343      * declared class, this method returns {@code true} if the specified
   344      * {@code Object} argument is an instance of the represented class (or
   345      * of any of its subclasses); it returns {@code false} otherwise. If
   346      * this {@code Class} object represents an array class, this method
   347      * returns {@code true} if the specified {@code Object} argument
   348      * can be converted to an object of the array class by an identity
   349      * conversion or by a widening reference conversion; it returns
   350      * {@code false} otherwise. If this {@code Class} object
   351      * represents an interface, this method returns {@code true} if the
   352      * class or any superclass of the specified {@code Object} argument
   353      * implements this interface; it returns {@code false} otherwise. If
   354      * this {@code Class} object represents a primitive type, this method
   355      * returns {@code false}.
   356      *
   357      * @param   obj the object to check
   358      * @return  true if {@code obj} is an instance of this class
   359      *
   360      * @since JDK1.1
   361      */
   362     public boolean isInstance(Object obj) {
   363         if (obj == null) {
   364             return false;
   365         }
   366         if (isArray()) {
   367             return isAssignableFrom(obj.getClass());
   368         }
   369         
   370         String prop = "$instOf_" + getName().replace('.', '_');
   371         return hasProperty(obj, prop);
   372     }
   373     
   374     @JavaScriptBody(args = { "who", "prop" }, body = 
   375         "if (who[prop]) return true; else return false;"
   376     )
   377     private static native boolean hasProperty(Object who, String prop);
   378 
   379 
   380     /**
   381      * Determines if the class or interface represented by this
   382      * {@code Class} object is either the same as, or is a superclass or
   383      * superinterface of, the class or interface represented by the specified
   384      * {@code Class} parameter. It returns {@code true} if so;
   385      * otherwise it returns {@code false}. If this {@code Class}
   386      * object represents a primitive type, this method returns
   387      * {@code true} if the specified {@code Class} parameter is
   388      * exactly this {@code Class} object; otherwise it returns
   389      * {@code false}.
   390      *
   391      * <p> Specifically, this method tests whether the type represented by the
   392      * specified {@code Class} parameter can be converted to the type
   393      * represented by this {@code Class} object via an identity conversion
   394      * or via a widening reference conversion. See <em>The Java Language
   395      * Specification</em>, sections 5.1.1 and 5.1.4 , for details.
   396      *
   397      * @param cls the {@code Class} object to be checked
   398      * @return the {@code boolean} value indicating whether objects of the
   399      * type {@code cls} can be assigned to objects of this class
   400      * @exception NullPointerException if the specified Class parameter is
   401      *            null.
   402      * @since JDK1.1
   403      */
   404     public boolean isAssignableFrom(Class<?> cls) {
   405         if (this == cls) {
   406             return true;
   407         }
   408         
   409         if (isArray()) {
   410             final Class<?> cmpType = cls.getComponentType();
   411             if (isPrimitive()) {
   412                 return this == cmpType;
   413             }
   414             return cmpType != null && getComponentType().isAssignableFrom(cmpType);
   415         }
   416         if (isPrimitive()) {
   417             return false;
   418         } else {
   419             if (cls.isPrimitive()) {
   420                 return false;
   421             }
   422             String prop = "$instOf_" + getName().replace('.', '_');
   423             return hasCnstrProperty(cls, prop);
   424         }
   425     }
   426 
   427     @JavaScriptBody(args = { "who", "prop" }, body = 
   428         "if (who.cnstr.prototype[prop]) return true; else return false;"
   429     )
   430     private static native boolean hasCnstrProperty(Object who, String prop);
   431     
   432     
   433     /**
   434      * Determines if the specified {@code Class} object represents an
   435      * interface type.
   436      *
   437      * @return  {@code true} if this object represents an interface;
   438      *          {@code false} otherwise.
   439      */
   440     public boolean isInterface() {
   441         return (getAccess() & 0x200) != 0;
   442     }
   443     
   444     @JavaScriptBody(args = {}, body = "return this.access;")
   445     private native int getAccess();
   446 
   447 
   448     /**
   449      * Determines if this {@code Class} object represents an array class.
   450      *
   451      * @return  {@code true} if this object represents an array class;
   452      *          {@code false} otherwise.
   453      * @since   JDK1.1
   454      */
   455     public boolean isArray() {
   456         return hasProperty(this, "array"); // NOI18N
   457     }
   458 
   459 
   460     /**
   461      * Determines if the specified {@code Class} object represents a
   462      * primitive type.
   463      *
   464      * <p> There are nine predefined {@code Class} objects to represent
   465      * the eight primitive types and void.  These are created by the Java
   466      * Virtual Machine, and have the same names as the primitive types that
   467      * they represent, namely {@code boolean}, {@code byte},
   468      * {@code char}, {@code short}, {@code int},
   469      * {@code long}, {@code float}, and {@code double}.
   470      *
   471      * <p> These objects may only be accessed via the following public static
   472      * final variables, and are the only {@code Class} objects for which
   473      * this method returns {@code true}.
   474      *
   475      * @return true if and only if this class represents a primitive type
   476      *
   477      * @see     java.lang.Boolean#TYPE
   478      * @see     java.lang.Character#TYPE
   479      * @see     java.lang.Byte#TYPE
   480      * @see     java.lang.Short#TYPE
   481      * @see     java.lang.Integer#TYPE
   482      * @see     java.lang.Long#TYPE
   483      * @see     java.lang.Float#TYPE
   484      * @see     java.lang.Double#TYPE
   485      * @see     java.lang.Void#TYPE
   486      * @since JDK1.1
   487      */
   488     @JavaScriptBody(args = {}, body = 
   489            "if (this.primitive) return true;"
   490         + "else return false;"
   491     )
   492     public native boolean isPrimitive();
   493 
   494     /**
   495      * Returns true if this {@code Class} object represents an annotation
   496      * type.  Note that if this method returns true, {@link #isInterface()}
   497      * would also return true, as all annotation types are also interfaces.
   498      *
   499      * @return {@code true} if this class object represents an annotation
   500      *      type; {@code false} otherwise
   501      * @since 1.5
   502      */
   503     public boolean isAnnotation() {
   504         return (getModifiers() & ANNOTATION) != 0;
   505     }
   506 
   507     /**
   508      * Returns {@code true} if this class is a synthetic class;
   509      * returns {@code false} otherwise.
   510      * @return {@code true} if and only if this class is a synthetic class as
   511      *         defined by the Java Language Specification.
   512      * @since 1.5
   513      */
   514     public boolean isSynthetic() {
   515         return (getModifiers() & SYNTHETIC) != 0;
   516     }
   517 
   518     /**
   519      * Returns the  name of the entity (class, interface, array class,
   520      * primitive type, or void) represented by this {@code Class} object,
   521      * as a {@code String}.
   522      *
   523      * <p> If this class object represents a reference type that is not an
   524      * array type then the binary name of the class is returned, as specified
   525      * by
   526      * <cite>The Java&trade; Language Specification</cite>.
   527      *
   528      * <p> If this class object represents a primitive type or void, then the
   529      * name returned is a {@code String} equal to the Java language
   530      * keyword corresponding to the primitive type or void.
   531      *
   532      * <p> If this class object represents a class of arrays, then the internal
   533      * form of the name consists of the name of the element type preceded by
   534      * one or more '{@code [}' characters representing the depth of the array
   535      * nesting.  The encoding of element type names is as follows:
   536      *
   537      * <blockquote><table summary="Element types and encodings">
   538      * <tr><th> Element Type <th> &nbsp;&nbsp;&nbsp; <th> Encoding
   539      * <tr><td> boolean      <td> &nbsp;&nbsp;&nbsp; <td align=center> Z
   540      * <tr><td> byte         <td> &nbsp;&nbsp;&nbsp; <td align=center> B
   541      * <tr><td> char         <td> &nbsp;&nbsp;&nbsp; <td align=center> C
   542      * <tr><td> class or interface
   543      *                       <td> &nbsp;&nbsp;&nbsp; <td align=center> L<i>classname</i>;
   544      * <tr><td> double       <td> &nbsp;&nbsp;&nbsp; <td align=center> D
   545      * <tr><td> float        <td> &nbsp;&nbsp;&nbsp; <td align=center> F
   546      * <tr><td> int          <td> &nbsp;&nbsp;&nbsp; <td align=center> I
   547      * <tr><td> long         <td> &nbsp;&nbsp;&nbsp; <td align=center> J
   548      * <tr><td> short        <td> &nbsp;&nbsp;&nbsp; <td align=center> S
   549      * </table></blockquote>
   550      *
   551      * <p> The class or interface name <i>classname</i> is the binary name of
   552      * the class specified above.
   553      *
   554      * <p> Examples:
   555      * <blockquote><pre>
   556      * String.class.getName()
   557      *     returns "java.lang.String"
   558      * byte.class.getName()
   559      *     returns "byte"
   560      * (new Object[3]).getClass().getName()
   561      *     returns "[Ljava.lang.Object;"
   562      * (new int[3][4][5][6][7][8][9]).getClass().getName()
   563      *     returns "[[[[[[[I"
   564      * </pre></blockquote>
   565      *
   566      * @return  the name of the class or interface
   567      *          represented by this object.
   568      */
   569     public String getName() {
   570         return jvmName().replace('/', '.');
   571     }
   572 
   573     @JavaScriptBody(args = {}, body = "return this.jvmName;")
   574     private native String jvmName();
   575 
   576     
   577     /**
   578      * Returns an array of {@code TypeVariable} objects that represent the
   579      * type variables declared by the generic declaration represented by this
   580      * {@code GenericDeclaration} object, in declaration order.  Returns an
   581      * array of length 0 if the underlying generic declaration declares no type
   582      * variables.
   583      *
   584      * @return an array of {@code TypeVariable} objects that represent
   585      *     the type variables declared by this generic declaration
   586      * @throws java.lang.reflect.GenericSignatureFormatError if the generic
   587      *     signature of this generic declaration does not conform to
   588      *     the format specified in
   589      *     <cite>The Java&trade; Virtual Machine Specification</cite>
   590      * @since 1.5
   591      */
   592     public TypeVariable<Class<T>>[] getTypeParameters() {
   593         throw new UnsupportedOperationException();
   594     }
   595  
   596     /**
   597      * Returns the {@code Class} representing the superclass of the entity
   598      * (class, interface, primitive type or void) represented by this
   599      * {@code Class}.  If this {@code Class} represents either the
   600      * {@code Object} class, an interface, a primitive type, or void, then
   601      * null is returned.  If this object represents an array class then the
   602      * {@code Class} object representing the {@code Object} class is
   603      * returned.
   604      *
   605      * @return the superclass of the class represented by this object.
   606      */
   607     @JavaScriptBody(args = {}, body = "return this.superclass;")
   608     public native Class<? super T> getSuperclass();
   609 
   610     /**
   611      * Returns the Java language modifiers for this class or interface, encoded
   612      * in an integer. The modifiers consist of the Java Virtual Machine's
   613      * constants for {@code public}, {@code protected},
   614      * {@code private}, {@code final}, {@code static},
   615      * {@code abstract} and {@code interface}; they should be decoded
   616      * using the methods of class {@code Modifier}.
   617      *
   618      * <p> If the underlying class is an array class, then its
   619      * {@code public}, {@code private} and {@code protected}
   620      * modifiers are the same as those of its component type.  If this
   621      * {@code Class} represents a primitive type or void, its
   622      * {@code public} modifier is always {@code true}, and its
   623      * {@code protected} and {@code private} modifiers are always
   624      * {@code false}. If this object represents an array class, a
   625      * primitive type or void, then its {@code final} modifier is always
   626      * {@code true} and its interface modifier is always
   627      * {@code false}. The values of its other modifiers are not determined
   628      * by this specification.
   629      *
   630      * <p> The modifier encodings are defined in <em>The Java Virtual Machine
   631      * Specification</em>, table 4.1.
   632      *
   633      * @return the {@code int} representing the modifiers for this class
   634      * @see     java.lang.reflect.Modifier
   635      * @since JDK1.1
   636      */
   637     public int getModifiers() {
   638         return getAccess();
   639     }
   640 
   641     /**
   642      * If the class or interface represented by this {@code Class} object
   643      * is a member of another class, returns the {@code Class} object
   644      * representing the class in which it was declared.  This method returns
   645      * null if this class or interface is not a member of any other class.  If
   646      * this {@code Class} object represents an array class, a primitive
   647      * type, or void,then this method returns null.
   648      *
   649      * @return the declaring class for this class
   650      * @since JDK1.1
   651      */
   652     public Class<?> getDeclaringClass() {
   653         throw new SecurityException();
   654     }
   655 
   656     /**
   657      * Returns the simple name of the underlying class as given in the
   658      * source code. Returns an empty string if the underlying class is
   659      * anonymous.
   660      *
   661      * <p>The simple name of an array is the simple name of the
   662      * component type with "[]" appended.  In particular the simple
   663      * name of an array whose component type is anonymous is "[]".
   664      *
   665      * @return the simple name of the underlying class
   666      * @since 1.5
   667      */
   668     public String getSimpleName() {
   669         if (isArray())
   670             return getComponentType().getSimpleName()+"[]";
   671 
   672         String simpleName = getSimpleBinaryName();
   673         if (simpleName == null) { // top level class
   674             simpleName = getName();
   675             return simpleName.substring(simpleName.lastIndexOf(".")+1); // strip the package name
   676         }
   677         // According to JLS3 "Binary Compatibility" (13.1) the binary
   678         // name of non-package classes (not top level) is the binary
   679         // name of the immediately enclosing class followed by a '$' followed by:
   680         // (for nested and inner classes): the simple name.
   681         // (for local classes): 1 or more digits followed by the simple name.
   682         // (for anonymous classes): 1 or more digits.
   683 
   684         // Since getSimpleBinaryName() will strip the binary name of
   685         // the immediatly enclosing class, we are now looking at a
   686         // string that matches the regular expression "\$[0-9]*"
   687         // followed by a simple name (considering the simple of an
   688         // anonymous class to be the empty string).
   689 
   690         // Remove leading "\$[0-9]*" from the name
   691         int length = simpleName.length();
   692         if (length < 1 || simpleName.charAt(0) != '$')
   693             throw new IllegalStateException("Malformed class name");
   694         int index = 1;
   695         while (index < length && isAsciiDigit(simpleName.charAt(index)))
   696             index++;
   697         // Eventually, this is the empty string iff this is an anonymous class
   698         return simpleName.substring(index);
   699     }
   700 
   701     /**
   702      * Returns the "simple binary name" of the underlying class, i.e.,
   703      * the binary name without the leading enclosing class name.
   704      * Returns {@code null} if the underlying class is a top level
   705      * class.
   706      */
   707     private String getSimpleBinaryName() {
   708         Class<?> enclosingClass = null; // XXX getEnclosingClass();
   709         if (enclosingClass == null) // top level class
   710             return null;
   711         // Otherwise, strip the enclosing class' name
   712         try {
   713             return getName().substring(enclosingClass.getName().length());
   714         } catch (IndexOutOfBoundsException ex) {
   715             throw new IllegalStateException("Malformed class name");
   716         }
   717     }
   718 
   719     /**
   720      * Returns an array containing {@code Field} objects reflecting all
   721      * the accessible public fields of the class or interface represented by
   722      * this {@code Class} object.  The elements in the array returned are
   723      * not sorted and are not in any particular order.  This method returns an
   724      * array of length 0 if the class or interface has no accessible public
   725      * fields, or if it represents an array class, a primitive type, or void.
   726      *
   727      * <p> Specifically, if this {@code Class} object represents a class,
   728      * this method returns the public fields of this class and of all its
   729      * superclasses.  If this {@code Class} object represents an
   730      * interface, this method returns the fields of this interface and of all
   731      * its superinterfaces.
   732      *
   733      * <p> The implicit length field for array class is not reflected by this
   734      * method. User code should use the methods of class {@code Array} to
   735      * manipulate arrays.
   736      *
   737      * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.3.
   738      *
   739      * @return the array of {@code Field} objects representing the
   740      * public fields
   741      * @exception  SecurityException
   742      *             If a security manager, <i>s</i>, is present and any of the
   743      *             following conditions is met:
   744      *
   745      *             <ul>
   746      *
   747      *             <li> invocation of
   748      *             {@link SecurityManager#checkMemberAccess
   749      *             s.checkMemberAccess(this, Member.PUBLIC)} denies
   750      *             access to the fields within this class
   751      *
   752      *             <li> the caller's class loader is not the same as or an
   753      *             ancestor of the class loader for the current class and
   754      *             invocation of {@link SecurityManager#checkPackageAccess
   755      *             s.checkPackageAccess()} denies access to the package
   756      *             of this class
   757      *
   758      *             </ul>
   759      *
   760      * @since JDK1.1
   761      */
   762     public Field[] getFields() throws SecurityException {
   763         throw new SecurityException();
   764     }
   765 
   766     /**
   767      * Returns an array containing {@code Method} objects reflecting all
   768      * the public <em>member</em> methods of the class or interface represented
   769      * by this {@code Class} object, including those declared by the class
   770      * or interface and those inherited from superclasses and
   771      * superinterfaces.  Array classes return all the (public) member methods
   772      * inherited from the {@code Object} class.  The elements in the array
   773      * returned are not sorted and are not in any particular order.  This
   774      * method returns an array of length 0 if this {@code Class} object
   775      * represents a class or interface that has no public member methods, or if
   776      * this {@code Class} object represents a primitive type or void.
   777      *
   778      * <p> The class initialization method {@code <clinit>} is not
   779      * included in the returned array. If the class declares multiple public
   780      * member methods with the same parameter types, they are all included in
   781      * the returned array.
   782      *
   783      * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.4.
   784      *
   785      * @return the array of {@code Method} objects representing the
   786      * public methods of this class
   787      * @exception  SecurityException
   788      *             If a security manager, <i>s</i>, is present and any of the
   789      *             following conditions is met:
   790      *
   791      *             <ul>
   792      *
   793      *             <li> invocation of
   794      *             {@link SecurityManager#checkMemberAccess
   795      *             s.checkMemberAccess(this, Member.PUBLIC)} denies
   796      *             access to the methods within this class
   797      *
   798      *             <li> the caller's class loader is not the same as or an
   799      *             ancestor of the class loader for the current class and
   800      *             invocation of {@link SecurityManager#checkPackageAccess
   801      *             s.checkPackageAccess()} denies access to the package
   802      *             of this class
   803      *
   804      *             </ul>
   805      *
   806      * @since JDK1.1
   807      */
   808     public Method[] getMethods() throws SecurityException {
   809         return MethodImpl.findMethods(this, 0x01);
   810     }
   811 
   812     /**
   813      * Returns a {@code Field} object that reflects the specified public
   814      * member field of the class or interface represented by this
   815      * {@code Class} object. The {@code name} parameter is a
   816      * {@code String} specifying the simple name of the desired field.
   817      *
   818      * <p> The field to be reflected is determined by the algorithm that
   819      * follows.  Let C be the class represented by this object:
   820      * <OL>
   821      * <LI> If C declares a public field with the name specified, that is the
   822      *      field to be reflected.</LI>
   823      * <LI> If no field was found in step 1 above, this algorithm is applied
   824      *      recursively to each direct superinterface of C. The direct
   825      *      superinterfaces are searched in the order they were declared.</LI>
   826      * <LI> If no field was found in steps 1 and 2 above, and C has a
   827      *      superclass S, then this algorithm is invoked recursively upon S.
   828      *      If C has no superclass, then a {@code NoSuchFieldException}
   829      *      is thrown.</LI>
   830      * </OL>
   831      *
   832      * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.3.
   833      *
   834      * @param name the field name
   835      * @return  the {@code Field} object of this class specified by
   836      * {@code name}
   837      * @exception NoSuchFieldException if a field with the specified name is
   838      *              not found.
   839      * @exception NullPointerException if {@code name} is {@code null}
   840      * @exception  SecurityException
   841      *             If a security manager, <i>s</i>, is present and any of the
   842      *             following conditions is met:
   843      *
   844      *             <ul>
   845      *
   846      *             <li> invocation of
   847      *             {@link SecurityManager#checkMemberAccess
   848      *             s.checkMemberAccess(this, Member.PUBLIC)} denies
   849      *             access to the field
   850      *
   851      *             <li> the caller's class loader is not the same as or an
   852      *             ancestor of the class loader for the current class and
   853      *             invocation of {@link SecurityManager#checkPackageAccess
   854      *             s.checkPackageAccess()} denies access to the package
   855      *             of this class
   856      *
   857      *             </ul>
   858      *
   859      * @since JDK1.1
   860      */
   861     public Field getField(String name)
   862         throws SecurityException {
   863         throw new SecurityException();
   864     }
   865     
   866     
   867     /**
   868      * Returns a {@code Method} object that reflects the specified public
   869      * member method of the class or interface represented by this
   870      * {@code Class} object. The {@code name} parameter is a
   871      * {@code String} specifying the simple name of the desired method. The
   872      * {@code parameterTypes} parameter is an array of {@code Class}
   873      * objects that identify the method's formal parameter types, in declared
   874      * order. If {@code parameterTypes} is {@code null}, it is
   875      * treated as if it were an empty array.
   876      *
   877      * <p> If the {@code name} is "{@code <init>};"or "{@code <clinit>}" a
   878      * {@code NoSuchMethodException} is raised. Otherwise, the method to
   879      * be reflected is determined by the algorithm that follows.  Let C be the
   880      * class represented by this object:
   881      * <OL>
   882      * <LI> C is searched for any <I>matching methods</I>. If no matching
   883      *      method is found, the algorithm of step 1 is invoked recursively on
   884      *      the superclass of C.</LI>
   885      * <LI> If no method was found in step 1 above, the superinterfaces of C
   886      *      are searched for a matching method. If any such method is found, it
   887      *      is reflected.</LI>
   888      * </OL>
   889      *
   890      * To find a matching method in a class C:&nbsp; If C declares exactly one
   891      * public method with the specified name and exactly the same formal
   892      * parameter types, that is the method reflected. If more than one such
   893      * method is found in C, and one of these methods has a return type that is
   894      * more specific than any of the others, that method is reflected;
   895      * otherwise one of the methods is chosen arbitrarily.
   896      *
   897      * <p>Note that there may be more than one matching method in a
   898      * class because while the Java language forbids a class to
   899      * declare multiple methods with the same signature but different
   900      * return types, the Java virtual machine does not.  This
   901      * increased flexibility in the virtual machine can be used to
   902      * implement various language features.  For example, covariant
   903      * returns can be implemented with {@linkplain
   904      * java.lang.reflect.Method#isBridge bridge methods}; the bridge
   905      * method and the method being overridden would have the same
   906      * signature but different return types.
   907      *
   908      * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.4.
   909      *
   910      * @param name the name of the method
   911      * @param parameterTypes the list of parameters
   912      * @return the {@code Method} object that matches the specified
   913      * {@code name} and {@code parameterTypes}
   914      * @exception NoSuchMethodException if a matching method is not found
   915      *            or if the name is "&lt;init&gt;"or "&lt;clinit&gt;".
   916      * @exception NullPointerException if {@code name} is {@code null}
   917      * @exception  SecurityException
   918      *             If a security manager, <i>s</i>, is present and any of the
   919      *             following conditions is met:
   920      *
   921      *             <ul>
   922      *
   923      *             <li> invocation of
   924      *             {@link SecurityManager#checkMemberAccess
   925      *             s.checkMemberAccess(this, Member.PUBLIC)} denies
   926      *             access to the method
   927      *
   928      *             <li> the caller's class loader is not the same as or an
   929      *             ancestor of the class loader for the current class and
   930      *             invocation of {@link SecurityManager#checkPackageAccess
   931      *             s.checkPackageAccess()} denies access to the package
   932      *             of this class
   933      *
   934      *             </ul>
   935      *
   936      * @since JDK1.1
   937      */
   938     public Method getMethod(String name, Class<?>... parameterTypes)
   939         throws SecurityException, NoSuchMethodException {
   940         Method m = MethodImpl.findMethod(this, name, parameterTypes);
   941         if (m == null) {
   942             StringBuilder sb = new StringBuilder();
   943             sb.append(getName()).append('.').append(name).append('(');
   944             String sep = "";
   945             for (int i = 0; i < parameterTypes.length; i++) {
   946                 sb.append(sep).append(parameterTypes[i].getName());
   947                 sep = ", ";
   948             }
   949             sb.append(')');
   950             throw new NoSuchMethodException(sb.toString());
   951         }
   952         return m;
   953     }
   954     
   955     /**
   956      * Returns an array of {@code Method} objects reflecting all the
   957      * methods declared by the class or interface represented by this
   958      * {@code Class} object. This includes public, protected, default
   959      * (package) access, and private methods, but excludes inherited methods.
   960      * The elements in the array returned are not sorted and are not in any
   961      * particular order.  This method returns an array of length 0 if the class
   962      * or interface declares no methods, or if this {@code Class} object
   963      * represents a primitive type, an array class, or void.  The class
   964      * initialization method {@code <clinit>} is not included in the
   965      * returned array. If the class declares multiple public member methods
   966      * with the same parameter types, they are all included in the returned
   967      * array.
   968      *
   969      * <p> See <em>The Java Language Specification</em>, section 8.2.
   970      *
   971      * @return    the array of {@code Method} objects representing all the
   972      * declared methods of this class
   973      * @exception  SecurityException
   974      *             If a security manager, <i>s</i>, is present and any of the
   975      *             following conditions is met:
   976      *
   977      *             <ul>
   978      *
   979      *             <li> invocation of
   980      *             {@link SecurityManager#checkMemberAccess
   981      *             s.checkMemberAccess(this, Member.DECLARED)} denies
   982      *             access to the declared methods within this class
   983      *
   984      *             <li> the caller's class loader is not the same as or an
   985      *             ancestor of the class loader for the current class and
   986      *             invocation of {@link SecurityManager#checkPackageAccess
   987      *             s.checkPackageAccess()} denies access to the package
   988      *             of this class
   989      *
   990      *             </ul>
   991      *
   992      * @since JDK1.1
   993      */
   994     public Method[] getDeclaredMethods() throws SecurityException {
   995         throw new SecurityException();
   996     }
   997     
   998     /**
   999      * Returns an array of {@code Field} objects reflecting all the fields
  1000      * declared by the class or interface represented by this
  1001      * {@code Class} object. This includes public, protected, default
  1002      * (package) access, and private fields, but excludes inherited fields.
  1003      * The elements in the array returned are not sorted and are not in any
  1004      * particular order.  This method returns an array of length 0 if the class
  1005      * or interface declares no fields, or if this {@code Class} object
  1006      * represents a primitive type, an array class, or void.
  1007      *
  1008      * <p> See <em>The Java Language Specification</em>, sections 8.2 and 8.3.
  1009      *
  1010      * @return    the array of {@code Field} objects representing all the
  1011      * declared fields of this class
  1012      * @exception  SecurityException
  1013      *             If a security manager, <i>s</i>, is present and any of the
  1014      *             following conditions is met:
  1015      *
  1016      *             <ul>
  1017      *
  1018      *             <li> invocation of
  1019      *             {@link SecurityManager#checkMemberAccess
  1020      *             s.checkMemberAccess(this, Member.DECLARED)} denies
  1021      *             access to the declared fields within this class
  1022      *
  1023      *             <li> the caller's class loader is not the same as or an
  1024      *             ancestor of the class loader for the current class and
  1025      *             invocation of {@link SecurityManager#checkPackageAccess
  1026      *             s.checkPackageAccess()} denies access to the package
  1027      *             of this class
  1028      *
  1029      *             </ul>
  1030      *
  1031      * @since JDK1.1
  1032      */
  1033     public Field[] getDeclaredFields() throws SecurityException {
  1034         throw new SecurityException();
  1035     }
  1036 
  1037     /**
  1038      * <b>Bck2Brwsr</b> emulation can only seek public methods, otherwise it
  1039      * throws a {@code SecurityException}.
  1040      * <p>
  1041      * Returns a {@code Method} object that reflects the specified
  1042      * declared method of the class or interface represented by this
  1043      * {@code Class} object. The {@code name} parameter is a
  1044      * {@code String} that specifies the simple name of the desired
  1045      * method, and the {@code parameterTypes} parameter is an array of
  1046      * {@code Class} objects that identify the method's formal parameter
  1047      * types, in declared order.  If more than one method with the same
  1048      * parameter types is declared in a class, and one of these methods has a
  1049      * return type that is more specific than any of the others, that method is
  1050      * returned; otherwise one of the methods is chosen arbitrarily.  If the
  1051      * name is "&lt;init&gt;"or "&lt;clinit&gt;" a {@code NoSuchMethodException}
  1052      * is raised.
  1053      *
  1054      * @param name the name of the method
  1055      * @param parameterTypes the parameter array
  1056      * @return    the {@code Method} object for the method of this class
  1057      * matching the specified name and parameters
  1058      * @exception NoSuchMethodException if a matching method is not found.
  1059      * @exception NullPointerException if {@code name} is {@code null}
  1060      * @exception  SecurityException
  1061      *             If a security manager, <i>s</i>, is present and any of the
  1062      *             following conditions is met:
  1063      *
  1064      *             <ul>
  1065      *
  1066      *             <li> invocation of
  1067      *             {@link SecurityManager#checkMemberAccess
  1068      *             s.checkMemberAccess(this, Member.DECLARED)} denies
  1069      *             access to the declared method
  1070      *
  1071      *             <li> the caller's class loader is not the same as or an
  1072      *             ancestor of the class loader for the current class and
  1073      *             invocation of {@link SecurityManager#checkPackageAccess
  1074      *             s.checkPackageAccess()} denies access to the package
  1075      *             of this class
  1076      *
  1077      *             </ul>
  1078      *
  1079      * @since JDK1.1
  1080      */
  1081     public Method getDeclaredMethod(String name, Class<?>... parameterTypes)
  1082     throws NoSuchMethodException, SecurityException {
  1083         try {
  1084             return getMethod(name, parameterTypes);
  1085         } catch (NoSuchMethodException ex) {
  1086             throw new SecurityException();
  1087         }
  1088     }
  1089 
  1090     /**
  1091      * Returns a {@code Field} object that reflects the specified declared
  1092      * field of the class or interface represented by this {@code Class}
  1093      * object. The {@code name} parameter is a {@code String} that
  1094      * specifies the simple name of the desired field.  Note that this method
  1095      * will not reflect the {@code length} field of an array class.
  1096      *
  1097      * @param name the name of the field
  1098      * @return the {@code Field} object for the specified field in this
  1099      * class
  1100      * @exception NoSuchFieldException if a field with the specified name is
  1101      *              not found.
  1102      * @exception NullPointerException if {@code name} is {@code null}
  1103      * @exception  SecurityException
  1104      *             If a security manager, <i>s</i>, is present and any of the
  1105      *             following conditions is met:
  1106      *
  1107      *             <ul>
  1108      *
  1109      *             <li> invocation of
  1110      *             {@link SecurityManager#checkMemberAccess
  1111      *             s.checkMemberAccess(this, Member.DECLARED)} denies
  1112      *             access to the declared field
  1113      *
  1114      *             <li> the caller's class loader is not the same as or an
  1115      *             ancestor of the class loader for the current class and
  1116      *             invocation of {@link SecurityManager#checkPackageAccess
  1117      *             s.checkPackageAccess()} denies access to the package
  1118      *             of this class
  1119      *
  1120      *             </ul>
  1121      *
  1122      * @since JDK1.1
  1123      */
  1124     public Field getDeclaredField(String name)
  1125     throws SecurityException {
  1126         throw new SecurityException();
  1127     }
  1128     
  1129     /**
  1130      * Returns an array containing {@code Constructor} objects reflecting
  1131      * all the public constructors of the class represented by this
  1132      * {@code Class} object.  An array of length 0 is returned if the
  1133      * class has no public constructors, or if the class is an array class, or
  1134      * if the class reflects a primitive type or void.
  1135      *
  1136      * Note that while this method returns an array of {@code
  1137      * Constructor<T>} objects (that is an array of constructors from
  1138      * this class), the return type of this method is {@code
  1139      * Constructor<?>[]} and <em>not</em> {@code Constructor<T>[]} as
  1140      * might be expected.  This less informative return type is
  1141      * necessary since after being returned from this method, the
  1142      * array could be modified to hold {@code Constructor} objects for
  1143      * different classes, which would violate the type guarantees of
  1144      * {@code Constructor<T>[]}.
  1145      *
  1146      * @return the array of {@code Constructor} objects representing the
  1147      *  public constructors of this class
  1148      * @exception  SecurityException
  1149      *             If a security manager, <i>s</i>, is present and any of the
  1150      *             following conditions is met:
  1151      *
  1152      *             <ul>
  1153      *
  1154      *             <li> invocation of
  1155      *             {@link SecurityManager#checkMemberAccess
  1156      *             s.checkMemberAccess(this, Member.PUBLIC)} denies
  1157      *             access to the constructors within this class
  1158      *
  1159      *             <li> the caller's class loader is not the same as or an
  1160      *             ancestor of the class loader for the current class and
  1161      *             invocation of {@link SecurityManager#checkPackageAccess
  1162      *             s.checkPackageAccess()} denies access to the package
  1163      *             of this class
  1164      *
  1165      *             </ul>
  1166      *
  1167      * @since JDK1.1
  1168      */
  1169     public Constructor<?>[] getConstructors() throws SecurityException {
  1170         return MethodImpl.findConstructors(this, 0x01);
  1171     }
  1172 
  1173     /**
  1174      * Returns a {@code Constructor} object that reflects the specified
  1175      * public constructor of the class represented by this {@code Class}
  1176      * object. The {@code parameterTypes} parameter is an array of
  1177      * {@code Class} objects that identify the constructor's formal
  1178      * parameter types, in declared order.
  1179      *
  1180      * If this {@code Class} object represents an inner class
  1181      * declared in a non-static context, the formal parameter types
  1182      * include the explicit enclosing instance as the first parameter.
  1183      *
  1184      * <p> The constructor to reflect is the public constructor of the class
  1185      * represented by this {@code Class} object whose formal parameter
  1186      * types match those specified by {@code parameterTypes}.
  1187      *
  1188      * @param parameterTypes the parameter array
  1189      * @return the {@code Constructor} object of the public constructor that
  1190      * matches the specified {@code parameterTypes}
  1191      * @exception NoSuchMethodException if a matching method is not found.
  1192      * @exception  SecurityException
  1193      *             If a security manager, <i>s</i>, is present and any of the
  1194      *             following conditions is met:
  1195      *
  1196      *             <ul>
  1197      *
  1198      *             <li> invocation of
  1199      *             {@link SecurityManager#checkMemberAccess
  1200      *             s.checkMemberAccess(this, Member.PUBLIC)} denies
  1201      *             access to the constructor
  1202      *
  1203      *             <li> the caller's class loader is not the same as or an
  1204      *             ancestor of the class loader for the current class and
  1205      *             invocation of {@link SecurityManager#checkPackageAccess
  1206      *             s.checkPackageAccess()} denies access to the package
  1207      *             of this class
  1208      *
  1209      *             </ul>
  1210      *
  1211      * @since JDK1.1
  1212      */
  1213     public Constructor<T> getConstructor(Class<?>... parameterTypes)
  1214     throws NoSuchMethodException, SecurityException {
  1215         Constructor c = MethodImpl.findConstructor(this, parameterTypes);
  1216         if (c == null) {
  1217             StringBuilder sb = new StringBuilder();
  1218             sb.append(getName()).append('(');
  1219             String sep = "";
  1220             for (int i = 0; i < parameterTypes.length; i++) {
  1221                 sb.append(sep).append(parameterTypes[i].getName());
  1222                 sep = ", ";
  1223             }
  1224             sb.append(')');
  1225             throw new NoSuchMethodException(sb.toString());
  1226         }
  1227         return c;
  1228     }
  1229 
  1230     /**
  1231      * Returns an array of {@code Constructor} objects reflecting all the
  1232      * constructors declared by the class represented by this
  1233      * {@code Class} object. These are public, protected, default
  1234      * (package) access, and private constructors.  The elements in the array
  1235      * returned are not sorted and are not in any particular order.  If the
  1236      * class has a default constructor, it is included in the returned array.
  1237      * This method returns an array of length 0 if this {@code Class}
  1238      * object represents an interface, a primitive type, an array class, or
  1239      * void.
  1240      *
  1241      * <p> See <em>The Java Language Specification</em>, section 8.2.
  1242      *
  1243      * @return    the array of {@code Constructor} objects representing all the
  1244      * declared constructors of this class
  1245      * @exception  SecurityException
  1246      *             If a security manager, <i>s</i>, is present and any of the
  1247      *             following conditions is met:
  1248      *
  1249      *             <ul>
  1250      *
  1251      *             <li> invocation of
  1252      *             {@link SecurityManager#checkMemberAccess
  1253      *             s.checkMemberAccess(this, Member.DECLARED)} denies
  1254      *             access to the declared constructors within this class
  1255      *
  1256      *             <li> the caller's class loader is not the same as or an
  1257      *             ancestor of the class loader for the current class and
  1258      *             invocation of {@link SecurityManager#checkPackageAccess
  1259      *             s.checkPackageAccess()} denies access to the package
  1260      *             of this class
  1261      *
  1262      *             </ul>
  1263      *
  1264      * @since JDK1.1
  1265      */
  1266     public Constructor<?>[] getDeclaredConstructors() throws SecurityException {
  1267         throw new SecurityException();
  1268     }
  1269     /**
  1270      * Returns a {@code Constructor} object that reflects the specified
  1271      * constructor of the class or interface represented by this
  1272      * {@code Class} object.  The {@code parameterTypes} parameter is
  1273      * an array of {@code Class} objects that identify the constructor's
  1274      * formal parameter types, in declared order.
  1275      *
  1276      * If this {@code Class} object represents an inner class
  1277      * declared in a non-static context, the formal parameter types
  1278      * include the explicit enclosing instance as the first parameter.
  1279      *
  1280      * @param parameterTypes the parameter array
  1281      * @return    The {@code Constructor} object for the constructor with the
  1282      * specified parameter list
  1283      * @exception NoSuchMethodException if a matching method is not found.
  1284      * @exception  SecurityException
  1285      *             If a security manager, <i>s</i>, is present and any of the
  1286      *             following conditions is met:
  1287      *
  1288      *             <ul>
  1289      *
  1290      *             <li> invocation of
  1291      *             {@link SecurityManager#checkMemberAccess
  1292      *             s.checkMemberAccess(this, Member.DECLARED)} denies
  1293      *             access to the declared constructor
  1294      *
  1295      *             <li> the caller's class loader is not the same as or an
  1296      *             ancestor of the class loader for the current class and
  1297      *             invocation of {@link SecurityManager#checkPackageAccess
  1298      *             s.checkPackageAccess()} denies access to the package
  1299      *             of this class
  1300      *
  1301      *             </ul>
  1302      *
  1303      * @since JDK1.1
  1304      */
  1305     public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)
  1306     throws NoSuchMethodException, SecurityException {
  1307         return getConstructor(parameterTypes);
  1308     }
  1309     
  1310     
  1311     /**
  1312      * Character.isDigit answers {@code true} to some non-ascii
  1313      * digits.  This one does not.
  1314      */
  1315     private static boolean isAsciiDigit(char c) {
  1316         return '0' <= c && c <= '9';
  1317     }
  1318 
  1319     /**
  1320      * Returns the canonical name of the underlying class as
  1321      * defined by the Java Language Specification.  Returns null if
  1322      * the underlying class does not have a canonical name (i.e., if
  1323      * it is a local or anonymous class or an array whose component
  1324      * type does not have a canonical name).
  1325      * @return the canonical name of the underlying class if it exists, and
  1326      * {@code null} otherwise.
  1327      * @since 1.5
  1328      */
  1329     public String getCanonicalName() {
  1330         if (isArray()) {
  1331             String canonicalName = getComponentType().getCanonicalName();
  1332             if (canonicalName != null)
  1333                 return canonicalName + "[]";
  1334             else
  1335                 return null;
  1336         }
  1337 //        if (isLocalOrAnonymousClass())
  1338 //            return null;
  1339 //        Class<?> enclosingClass = getEnclosingClass();
  1340         Class<?> enclosingClass = null;
  1341         if (enclosingClass == null) { // top level class
  1342             return getName();
  1343         } else {
  1344             String enclosingName = enclosingClass.getCanonicalName();
  1345             if (enclosingName == null)
  1346                 return null;
  1347             return enclosingName + "." + getSimpleName();
  1348         }
  1349     }
  1350 
  1351     /**
  1352      * Finds a resource with a given name.  The rules for searching resources
  1353      * associated with a given class are implemented by the defining
  1354      * {@linkplain ClassLoader class loader} of the class.  This method
  1355      * delegates to this object's class loader.  If this object was loaded by
  1356      * the bootstrap class loader, the method delegates to {@link
  1357      * ClassLoader#getSystemResourceAsStream}.
  1358      *
  1359      * <p> Before delegation, an absolute resource name is constructed from the
  1360      * given resource name using this algorithm:
  1361      *
  1362      * <ul>
  1363      *
  1364      * <li> If the {@code name} begins with a {@code '/'}
  1365      * (<tt>'&#92;u002f'</tt>), then the absolute name of the resource is the
  1366      * portion of the {@code name} following the {@code '/'}.
  1367      *
  1368      * <li> Otherwise, the absolute name is of the following form:
  1369      *
  1370      * <blockquote>
  1371      *   {@code modified_package_name/name}
  1372      * </blockquote>
  1373      *
  1374      * <p> Where the {@code modified_package_name} is the package name of this
  1375      * object with {@code '/'} substituted for {@code '.'}
  1376      * (<tt>'&#92;u002e'</tt>).
  1377      *
  1378      * </ul>
  1379      *
  1380      * @param  name name of the desired resource
  1381      * @return      A {@link java.io.InputStream} object or {@code null} if
  1382      *              no resource with this name is found
  1383      * @throws  NullPointerException If {@code name} is {@code null}
  1384      * @since  JDK1.1
  1385      */
  1386      public InputStream getResourceAsStream(String name) {
  1387         name = resolveName(name);
  1388         byte[] arr = ClassLoader.getResourceAsStream0(name, 0);
  1389         return arr == null ? null : new ByteArrayInputStream(arr);
  1390      }
  1391     
  1392     /**
  1393      * Finds a resource with a given name.  The rules for searching resources
  1394      * associated with a given class are implemented by the defining
  1395      * {@linkplain ClassLoader class loader} of the class.  This method
  1396      * delegates to this object's class loader.  If this object was loaded by
  1397      * the bootstrap class loader, the method delegates to {@link
  1398      * ClassLoader#getSystemResource}.
  1399      *
  1400      * <p> Before delegation, an absolute resource name is constructed from the
  1401      * given resource name using this algorithm:
  1402      *
  1403      * <ul>
  1404      *
  1405      * <li> If the {@code name} begins with a {@code '/'}
  1406      * (<tt>'&#92;u002f'</tt>), then the absolute name of the resource is the
  1407      * portion of the {@code name} following the {@code '/'}.
  1408      *
  1409      * <li> Otherwise, the absolute name is of the following form:
  1410      *
  1411      * <blockquote>
  1412      *   {@code modified_package_name/name}
  1413      * </blockquote>
  1414      *
  1415      * <p> Where the {@code modified_package_name} is the package name of this
  1416      * object with {@code '/'} substituted for {@code '.'}
  1417      * (<tt>'&#92;u002e'</tt>).
  1418      *
  1419      * </ul>
  1420      *
  1421      * @param  name name of the desired resource
  1422      * @return      A  {@link java.net.URL} object or {@code null} if no
  1423      *              resource with this name is found
  1424      * @since  JDK1.1
  1425      */
  1426     public java.net.URL getResource(String name) {
  1427         return newResourceURL(name, getResourceAsStream(name));
  1428     }
  1429 
  1430     static URL newResourceURL(String name, InputStream is) {
  1431         return is == null ? null : newResourceURL0(URL.class, "res:/" + name, is);
  1432     }
  1433     
  1434     @JavaScriptBody(args = { "url", "spec", "is" }, body = 
  1435         "var u = url.cnstr(true);\n"
  1436       + "u.constructor.cons__VLjava_lang_String_2Ljava_io_InputStream_2.call(u, spec, is);\n"
  1437       + "return u;"
  1438     )
  1439     private static native URL newResourceURL0(Class<URL> url, String spec, InputStream is);
  1440 
  1441    /**
  1442      * Add a package name prefix if the name is not absolute Remove leading "/"
  1443      * if name is absolute
  1444      */
  1445     private String resolveName(String name) {
  1446         if (name == null) {
  1447             return name;
  1448         }
  1449         if (!name.startsWith("/")) {
  1450             Class<?> c = this;
  1451             while (c.isArray()) {
  1452                 c = c.getComponentType();
  1453             }
  1454             String baseName = c.getName();
  1455             int index = baseName.lastIndexOf('.');
  1456             if (index != -1) {
  1457                 name = baseName.substring(0, index).replace('.', '/')
  1458                     +"/"+name;
  1459             }
  1460         } else {
  1461             name = name.substring(1);
  1462         }
  1463         return name;
  1464     }
  1465     
  1466     /**
  1467      * Returns the class loader for the class.  Some implementations may use
  1468      * null to represent the bootstrap class loader. This method will return
  1469      * null in such implementations if this class was loaded by the bootstrap
  1470      * class loader.
  1471      *
  1472      * <p> If a security manager is present, and the caller's class loader is
  1473      * not null and the caller's class loader is not the same as or an ancestor of
  1474      * the class loader for the class whose class loader is requested, then
  1475      * this method calls the security manager's {@code checkPermission}
  1476      * method with a {@code RuntimePermission("getClassLoader")}
  1477      * permission to ensure it's ok to access the class loader for the class.
  1478      *
  1479      * <p>If this object
  1480      * represents a primitive type or void, null is returned.
  1481      *
  1482      * @return  the class loader that loaded the class or interface
  1483      *          represented by this object.
  1484      * @throws SecurityException
  1485      *    if a security manager exists and its
  1486      *    {@code checkPermission} method denies
  1487      *    access to the class loader for the class.
  1488      * @see java.lang.ClassLoader
  1489      * @see SecurityManager#checkPermission
  1490      * @see java.lang.RuntimePermission
  1491      */
  1492     public ClassLoader getClassLoader() {
  1493         return ClassLoader.getSystemClassLoader();
  1494     }
  1495 
  1496     /**
  1497      * Determines the interfaces implemented by the class or interface
  1498      * represented by this object.
  1499      *
  1500      * <p> If this object represents a class, the return value is an array
  1501      * containing objects representing all interfaces implemented by the
  1502      * class. The order of the interface objects in the array corresponds to
  1503      * the order of the interface names in the {@code implements} clause
  1504      * of the declaration of the class represented by this object. For
  1505      * example, given the declaration:
  1506      * <blockquote>
  1507      * {@code class Shimmer implements FloorWax, DessertTopping { ... }}
  1508      * </blockquote>
  1509      * suppose the value of {@code s} is an instance of
  1510      * {@code Shimmer}; the value of the expression:
  1511      * <blockquote>
  1512      * {@code s.getClass().getInterfaces()[0]}
  1513      * </blockquote>
  1514      * is the {@code Class} object that represents interface
  1515      * {@code FloorWax}; and the value of:
  1516      * <blockquote>
  1517      * {@code s.getClass().getInterfaces()[1]}
  1518      * </blockquote>
  1519      * is the {@code Class} object that represents interface
  1520      * {@code DessertTopping}.
  1521      *
  1522      * <p> If this object represents an interface, the array contains objects
  1523      * representing all interfaces extended by the interface. The order of the
  1524      * interface objects in the array corresponds to the order of the interface
  1525      * names in the {@code extends} clause of the declaration of the
  1526      * interface represented by this object.
  1527      *
  1528      * <p> If this object represents a class or interface that implements no
  1529      * interfaces, the method returns an array of length 0.
  1530      *
  1531      * <p> If this object represents a primitive type or void, the method
  1532      * returns an array of length 0.
  1533      *
  1534      * @return an array of interfaces implemented by this class.
  1535      */
  1536     public native Class<?>[] getInterfaces();
  1537     
  1538     /**
  1539      * Returns the {@code Class} representing the component type of an
  1540      * array.  If this class does not represent an array class this method
  1541      * returns null.
  1542      *
  1543      * @return the {@code Class} representing the component type of this
  1544      * class if this class is an array
  1545      * @see     java.lang.reflect.Array
  1546      * @since JDK1.1
  1547      */
  1548     public Class<?> getComponentType() {
  1549         if (isArray()) {
  1550             try {
  1551                 Class<?> c = getComponentTypeByFnc();
  1552                 return c != null ? c : getComponentType0();
  1553             } catch (ClassNotFoundException cnfe) {
  1554                 throw new IllegalStateException(cnfe);
  1555             }
  1556         }
  1557         return null;
  1558     }
  1559     
  1560     @JavaScriptBody(args = {  }, body = 
  1561         "if (this.fnc) {\n"
  1562       + "  var c = this.fnc(false).constructor.$class;\n"
  1563 //      + "  java.lang.System.out.println('will call: ' + (!!this.fnc) + ' res: ' + c.jvmName);\n"
  1564       + "  if (c) return c;\n"
  1565       + "}\n"
  1566       + "return null;"
  1567     )
  1568     private native Class<?> getComponentTypeByFnc();
  1569 
  1570     private Class<?> getComponentType0() throws ClassNotFoundException {
  1571         String n = getName().substring(1);
  1572         switch (n.charAt(0)) {
  1573             case 'L': 
  1574                 n = n.substring(1, n.length() - 1);
  1575                 return Class.forName(n);
  1576             case 'I':
  1577                 return Integer.TYPE;
  1578             case 'J':
  1579                 return Long.TYPE;
  1580             case 'D':
  1581                 return Double.TYPE;
  1582             case 'F':
  1583                 return Float.TYPE;
  1584             case 'B':
  1585                 return Byte.TYPE;
  1586             case 'Z':
  1587                 return Boolean.TYPE;
  1588             case 'S':
  1589                 return Short.TYPE;
  1590             case 'V':
  1591                 return Void.TYPE;
  1592             case 'C':
  1593                 return Character.TYPE;
  1594             case '[':
  1595                 return defineArray(n, null);
  1596             default:
  1597                 throw new ClassNotFoundException("Unknown component type of " + getName());
  1598         }
  1599     }
  1600     
  1601     @JavaScriptBody(args = { "sig", "fnc" }, body = 
  1602         "if (!sig) sig = '[Ljava/lang/Object;';\n" +
  1603         "var c = Array[sig];\n" +
  1604         "if (!c) {\n" +
  1605         "  c = vm.java_lang_Class(true);\n" +
  1606         "  c.jvmName = sig;\n" +
  1607         "  c.superclass = vm.java_lang_Object(false).$class;\n" +
  1608         "  c.array = true;\n" +
  1609         "  Array[sig] = c;\n" +
  1610         "}\n" +
  1611         "if (!c.fnc) c.fnc = fnc;\n" +
  1612         "return c;"
  1613     )
  1614     private static native Class<?> defineArray(String sig, Object fnc);
  1615     
  1616     /**
  1617      * Returns true if and only if this class was declared as an enum in the
  1618      * source code.
  1619      *
  1620      * @return true if and only if this class was declared as an enum in the
  1621      *     source code
  1622      * @since 1.5
  1623      */
  1624     public boolean isEnum() {
  1625         // An enum must both directly extend java.lang.Enum and have
  1626         // the ENUM bit set; classes for specialized enum constants
  1627         // don't do the former.
  1628         return (this.getModifiers() & ENUM) != 0 &&
  1629         this.getSuperclass() == java.lang.Enum.class;
  1630     }
  1631 
  1632     /**
  1633      * Casts an object to the class or interface represented
  1634      * by this {@code Class} object.
  1635      *
  1636      * @param obj the object to be cast
  1637      * @return the object after casting, or null if obj is null
  1638      *
  1639      * @throws ClassCastException if the object is not
  1640      * null and is not assignable to the type T.
  1641      *
  1642      * @since 1.5
  1643      */
  1644     public T cast(Object obj) {
  1645         if (obj != null && !isInstance(obj))
  1646             throw new ClassCastException(cannotCastMsg(obj));
  1647         return (T) obj;
  1648     }
  1649 
  1650     private String cannotCastMsg(Object obj) {
  1651         return "Cannot cast " + obj.getClass().getName() + " to " + getName();
  1652     }
  1653 
  1654     /**
  1655      * Casts this {@code Class} object to represent a subclass of the class
  1656      * represented by the specified class object.  Checks that that the cast
  1657      * is valid, and throws a {@code ClassCastException} if it is not.  If
  1658      * this method succeeds, it always returns a reference to this class object.
  1659      *
  1660      * <p>This method is useful when a client needs to "narrow" the type of
  1661      * a {@code Class} object to pass it to an API that restricts the
  1662      * {@code Class} objects that it is willing to accept.  A cast would
  1663      * generate a compile-time warning, as the correctness of the cast
  1664      * could not be checked at runtime (because generic types are implemented
  1665      * by erasure).
  1666      *
  1667      * @return this {@code Class} object, cast to represent a subclass of
  1668      *    the specified class object.
  1669      * @throws ClassCastException if this {@code Class} object does not
  1670      *    represent a subclass of the specified class (here "subclass" includes
  1671      *    the class itself).
  1672      * @since 1.5
  1673      */
  1674     public <U> Class<? extends U> asSubclass(Class<U> clazz) {
  1675         if (clazz.isAssignableFrom(this))
  1676             return (Class<? extends U>) this;
  1677         else
  1678             throw new ClassCastException(this.toString());
  1679     }
  1680 
  1681     @JavaScriptBody(args = { "ac" }, 
  1682         body = 
  1683           "if (this.anno) {\n"
  1684         + "  var r = this.anno['L' + ac.jvmName + ';'];\n"
  1685         + "  if (typeof r === 'undefined') r = null;\n"
  1686         + "  return r;\n"
  1687         + "} else return null;\n"
  1688     )
  1689     private Object getAnnotationData(Class<?> annotationClass) {
  1690         throw new UnsupportedOperationException();
  1691     }
  1692     /**
  1693      * @throws NullPointerException {@inheritDoc}
  1694      * @since 1.5
  1695      */
  1696     public <A extends Annotation> A getAnnotation(Class<A> annotationClass) {
  1697         Object data = getAnnotationData(annotationClass);
  1698         return data == null ? null : AnnotationImpl.create(annotationClass, data);
  1699     }
  1700 
  1701     /**
  1702      * @throws NullPointerException {@inheritDoc}
  1703      * @since 1.5
  1704      */
  1705     @JavaScriptBody(args = { "ac" }, 
  1706         body = "if (this.anno && this.anno['L' + ac.jvmName + ';']) { return true; }"
  1707         + "else return false;"
  1708     )
  1709     public boolean isAnnotationPresent(
  1710         Class<? extends Annotation> annotationClass) {
  1711         if (annotationClass == null)
  1712             throw new NullPointerException();
  1713 
  1714         return getAnnotation(annotationClass) != null;
  1715     }
  1716 
  1717     @JavaScriptBody(args = {}, body = "return this.anno;")
  1718     private Object getAnnotationData() {
  1719         throw new UnsupportedOperationException();
  1720     }
  1721 
  1722     /**
  1723      * @since 1.5
  1724      */
  1725     public Annotation[] getAnnotations() {
  1726         Object data = getAnnotationData();
  1727         return data == null ? new Annotation[0] : AnnotationImpl.create(data);
  1728     }
  1729 
  1730     /**
  1731      * @since 1.5
  1732      */
  1733     public Annotation[] getDeclaredAnnotations()  {
  1734         throw new UnsupportedOperationException();
  1735     }
  1736 
  1737     @JavaScriptBody(args = "type", body = ""
  1738         + "var c = vm.java_lang_Class(true);"
  1739         + "c.jvmName = type;"
  1740         + "c.primitive = true;"
  1741         + "return c;"
  1742     )
  1743     native static Class getPrimitiveClass(String type);
  1744 
  1745     @JavaScriptBody(args = {}, body = 
  1746         "return this.desiredAssertionStatus ? this.desiredAssertionStatus : false;"
  1747     )
  1748     public native boolean desiredAssertionStatus();
  1749     
  1750     static void registerNatives() {
  1751         boolean assertsOn = false;
  1752         //       assert assertsOn = true;
  1753         if (assertsOn) {
  1754             try {
  1755                 Array.get(null, 0);
  1756             } catch (Throwable ex) {
  1757                 // ignore
  1758             }
  1759         }
  1760     }
  1761 
  1762     @JavaScriptBody(args = {}, body = "var p = vm.java_lang_Object(false);"
  1763             + "p.toString = function() { return this.toString__Ljava_lang_String_2(); };"
  1764     )
  1765     static native void registerToString();
  1766     
  1767     @JavaScriptBody(args = {"self"}, body
  1768             = "var c = self.constructor.$class;\n"
  1769             + "return c ? c : null;\n"
  1770     )
  1771     static native Class<?> classFor(Object self);
  1772     
  1773     @JavaScriptBody(args = { "self" }, body
  1774             = "if (self.$hashCode) return self.$hashCode;\n"
  1775             + "var h = self.computeHashCode__I ? self.computeHashCode__I() : Math.random() * Math.pow(2, 31);\n"
  1776             + "return self.$hashCode = h & h;"
  1777     )
  1778     static native int defaultHashCode(Object self);
  1779 
  1780     @JavaScriptBody(args = "self", body
  1781             = "\nif (!self['$instOf_java_lang_Cloneable']) {"
  1782             + "\n  return null;"
  1783             + "\n} else {"
  1784             + "\n  var clone = self.constructor(true);"
  1785             + "\n  var props = Object.getOwnPropertyNames(self);"
  1786             + "\n  for (var i = 0; i < props.length; i++) {"
  1787             + "\n    var p = props[i];"
  1788             + "\n    clone[p] = self[p];"
  1789             + "\n  };"
  1790             + "\n  return clone;"
  1791             + "\n}"
  1792     )
  1793     static native Object clone(Object self) throws CloneNotSupportedException;
  1794 
  1795     @JavaScriptOnly(name = "toJS", value = "function(v) {\n"
  1796         + "  if (v === null) return null;\n"
  1797         + "  if (Object.prototype.toString.call(v) === '[object Array]') {\n"
  1798         + "    return vm.org_apidesign_bck2brwsr_emul_lang_System(false).convArray__Ljava_lang_Object_2Ljava_lang_Object_2(v);\n"
  1799         + "  }\n"
  1800         + "  return v.valueOf();\n"
  1801         + "}\n"
  1802     )
  1803     static native int toJS();
  1804 
  1805     @JavaScriptOnly(name = "activate__Ljava_io_Closeable_2Lorg_apidesign_html_boot_spi_Fn$Presenter_2", value = "function() {\n"
  1806         + "  return vm.org_apidesign_bck2brwsr_emul_lang_System(false).activate__Ljava_io_Closeable_2();"
  1807         + "}\n"
  1808     )
  1809     static native int activate();
  1810     
  1811     private static Object bck2BrwsrCnvrt(Object o) {
  1812         if (o instanceof Throwable) {
  1813             return o;
  1814         }
  1815         final String msg = msg(o);
  1816         if (msg == null || msg.startsWith("TypeError")) {
  1817             return new NullPointerException(msg);
  1818         }
  1819         return new Throwable(msg);
  1820     }
  1821 
  1822     @JavaScriptBody(args = {"o"}, body = "return o ? o.toString() : null;")
  1823     private static native String msg(Object o);
  1824 
  1825     @JavaScriptOnly(name = "bck2BrwsrThrwrbl", value = "c.bck2BrwsrCnvrt__Ljava_lang_Object_2Ljava_lang_Object_2")
  1826     private static void bck2BrwsrCnvrtVM() {
  1827     }
  1828     
  1829 }