class.java

来自「This is a resource based on j2me embedde」· Java 代码 · 共 1,469 行 · 第 1/5 页

JAVA
1,469
字号
/* * @(#)Class.java	1.131 06/10/10 * * Copyright  1990-2008 Sun Microsystems, Inc. All Rights Reserved.   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER   *    * This program is free software; you can redistribute it and/or   * modify it under the terms of the GNU General Public License version   * 2 only, as published by the Free Software Foundation.    *    * This program is distributed in the hope that it will be useful, but   * WITHOUT ANY WARRANTY; without even the implied warranty of   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU   * General Public License version 2 for more details (a copy is   * included at /legal/license.txt).    *    * You should have received a copy of the GNU General Public License   * version 2 along with this work; if not, write to the Free Software   * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA   * 02110-1301 USA    *    * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa   * Clara, CA 95054 or visit www.sun.com if you need additional   * information or have any questions.  * */package java.lang;import java.lang.reflect.Member;import java.lang.reflect.Field;import java.lang.reflect.Method;import java.lang.reflect.Constructor;import java.lang.reflect.Modifier;import java.lang.reflect.InvocationTargetException;import java.io.InputStream;import java.io.ObjectStreamClass;import java.io.ObjectStreamField;import java.security.AccessController;import java.security.PrivilegedAction;import java.util.ArrayList;import java.util.List;import sun.security.util.SecurityConstants;import sun.misc.CVM;import java.util.WeakHashMap;import java.util.Map;import java.util.Collections;/** * Instances of the class <code>Class</code> represent classes and interfaces * in a running Java application.  Every array also belongs to a class that is * reflected as a <code>Class</code> object that is shared by all arrays with * the same element type and number of dimensions.  The primitive Java types * (<code>boolean</code>, <code>byte</code>, <code>char</code>, * <code>short</code>, <code>int</code>, <code>long</code>, * <code>float</code>, and <code>double</code>), and the keyword * <code>void</code> are also represented as <code>Class</code> objects. * * <p> <code>Class</code> has no public constructor. Instead <code>Class</code> * objects are constructed automatically by the Java Virtual Machine as classes * are loaded and by calls to the <code>defineClass</code> method in the class * loader. * * <p> The following example uses a <code>Class</code> object to print the * class name of an object: * * <p> <blockquote><pre> *     void printClassName(Object obj) { *         System.out.println("The class of " + obj + *                            " is " + obj.getClass().getName()); *     } * </pre></blockquote> *  * <p> It is also possible to get the <code>Class</code> object for a named * type (or for void) using a class literal  * (JLS Section <A HREF="http://java.sun.com/docs/books/jls/second_edition/html/expressions.doc.html#251530">15.8.2</A>).  * For example: * * <p> <blockquote><pre> *     System.out.println("The name of class Foo is: "+Foo.class.getName()); * </pre></blockquote> * * @author  unascribed * @version 1.135, 05/25/01 * @see     java.lang.ClassLoader#defineClass(byte[], int, int) * @since   JDK1.0 */public finalclass Class implements java.io.Serializable {    private int            classBlockPointer; /* Private pointer to cb */    private ClassLoader    loader; /* For GC purposes only! */    /* No need to do this if ROMized    private static native void registerNatives();    static {        registerNatives();    }    */    /*     * Constructor. Only the Java Virtual Machine creates Class     * objects.     */    private Class() {}    /**     * Converts the object to a string. The string representation is the     * string "class" or "interface", followed by a space, and then by the     * fully qualified name of the class in the format returned by     * <code>getName</code>.  If this <code>Class</code> object represents a     * primitive type, this method returns the name of the primitive type.  If     * this <code>Class</code> object represents void this method returns     * "void".     *     * @return a string representation of this class object.     */    public String toString() {        return (isInterface() ? "interface " : (isPrimitive() ? "" : "class "))            + getName();    }    /**     * Returns the <code>Class</code> object associated with the class or     * interface with the given string name.  Invoking this method is     * equivalent to:     *     * <blockquote><pre>     *  Class.forName(className, true, currentLoader)     * </pre></blockquote>     *     * where <code>currentLoader</code> denotes the defining class loader of     * the current class.     *     * <p> For example, the following code fragment returns the     * runtime <code>Class</code> descriptor for the class named     * <code>java.lang.Thread</code>:     *     * <blockquote><pre>     *   Class&nbsp;t&nbsp;= Class.forName("java.lang.Thread")     * </pre></blockquote>     * <p>     * A call to <tt>forName("X")</tt> causes the class named      * <tt>X</tt> to be initialized.     *     * @param      className   the fully qualified name of the desired class.     * @return     the <code>Class</code> object for the class with the     *             specified name.     * @exception LinkageError if the linkage fails     * @exception ExceptionInInitializerError if the initialization provoked     *            by this method fails     * @exception ClassNotFoundException if the class cannot be located     */    public static Class forName(String className)                 throws ClassNotFoundException {        return forName0(className, true, ClassLoader.getCallerClassLoader());    }    /**     * Returns the <code>Class</code> object associated with the class or     * interface with the given string name, using the given class loader.     * Given the fully qualified name for a class or interface (in the same     * format returned by <code>getName</code>) this method attempts to     * locate, load, and link the class or interface.  The specified class     * loader is used to load the class or interface.  If the parameter     * <code>loader</code> is null, the class is loaded through the bootstrap     * class loader.  The class is initialized only if the     * <code>initialize</code> parameter is <code>true</code> and if it has     * not been initialized earlier.     *     * <p> If <code>name</code> denotes a primitive type or void, an attempt     * will be made to locate a user-defined class in the unnamed package whose     * name is <code>name</code>. Therefore, this method cannot be used to     * obtain any of the <code>Class</code> objects representing primitive     * types or void.     *     * <p> If <code>name</code> denotes an array class, the component type of     * the array class is loaded but not initialized.     *     * <p> For example, in an instance method the expression:     *     * <blockquote><pre>     *  Class.forName("Foo")     * </pre></blockquote>     *     * is equivalent to:     *     * <blockquote><pre>     *  Class.forName("Foo", true, this.getClass().getClassLoader())     * </pre></blockquote>     *     * Note that this method throws errors related to loading, linking or     * initializing as specified in Sections 12.2, 12.3 and 12.4 of <em>The     * Java Language Specification</em>.     * Note that this method does not check whether the requested class      * is accessible to its caller.     *     * <p> If the <code>loader</code> is <code>null</code>, and a security     * manager is present, and the caller's class loader is not null, then this     * method calls the security manager's <code>checkPermission</code> method     * with a <code>RuntimePermission("getClassLoader")</code> permission to     * ensure it's ok to access the bootstrap class loader.     *     * @param name       fully qualified name of the desired class     * @param initialize whether the class must be initialized     * @param loader     class loader from which the class must be loaded     * @return           class object representing the desired class     *      * @exception LinkageError if the linkage fails     * @exception ExceptionInInitializerError if the initialization provoked     *            by this method fails     * @exception ClassNotFoundException if the class cannot be located by     *            the specified class loader     *     * @see 	  java.lang.Class#forName(String)      * @see 	  java.lang.ClassLoader     * @since 	  1.2     */    public static Class forName(String name, boolean initialize,				ClassLoader loader)        throws ClassNotFoundException    {	if (loader == null) {	    SecurityManager sm = System.getSecurityManager();	    if (sm != null) {		ClassLoader ccl = ClassLoader.getCallerClassLoader();		if (ccl != null) {		    sm.checkPermission(			SecurityConstants.GET_CLASSLOADER_PERMISSION);		}	    }	}	return forName0(name, initialize, loader);    }    /** Called after security checks have been made. */    private static native Class forName0(String name, boolean initialize,					 ClassLoader loader)	throws ClassNotFoundException;    /**     * Creates a new instance of the class represented by this <tt>Class</tt>     * object.  The class is instantiated as if by a <code>new</code>     * expression with an empty argument list.  The class is initialized if it     * has not already been initialized.     *     * <p>If there is a security manager, this method first calls the security     * manager's <code>checkMemberAccess</code> method with <code>this</code>     * and <code>Member.PUBLIC</code> as its arguments. If the class is in a     * package, then this method also calls the security manager's     * <code>checkPackageAccess</code> method with the package name as its     * argument. Either of these calls could result in a SecurityException.     *     * @return     a newly allocated instance of the class represented by this     *             object.     * @exception  IllegalAccessException  if the class or its nullary      *               constructor is not accessible.     * @exception  InstantiationException      *               if this <code>Class</code> represents an abstract class,     *               an interface, an array class, a primitive type, or void;     *               or if the class has no nullary constructor;     *               or if the instantiation fails for some other reason.     * @exception  ExceptionInInitializerError if the initialization     *               provoked by this method fails.     * @exception  SecurityException if there is no permission to create a new     *               instance.     *     */    public Object newInstance()        throws InstantiationException, IllegalAccessException    {	if (System.getSecurityManager() != null) {	    checkMemberAccess(Member.PUBLIC, ClassLoader.getCallerClassLoader());	}	int flags = Modifier.ABSTRACT | Modifier.INTERFACE;	if ((getModifiers() & flags) != 0 || isPrimitive()) {	    throw new InstantiationException(this.getName() + 					     " is an interface or abstract");	}	try {	    CVM.setContextArtificial();	    Constructor c = getConstructor0(new Class[0], Member.DECLARED);	    return c.newInstance(new Object[0]);	} catch (NoSuchMethodException e) {	    throw new InstantiationException(this.getName()+" has no appropriate constructor");	} catch (InvocationTargetException e) {	    // There should be a better way!  Maybe we need a	    // private entry point to the Constructor.newInstance()	    // implemenation that doesn't wrap things in	    // InvocationTargetException	    throw CVM.throwLocalException(e.getTargetException());

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?