objectstreamclass.java

来自「JAVA的一些源码 JAVA2 STANDARD EDITION DEVELO」· Java 代码 · 共 1,769 行 · 第 1/4 页

JAVA
1,769
字号
	String type = null;	if (clazz.isArray()) {	    Class cl = clazz;	    int dimensions = 0;	    while (cl.isArray()) {		dimensions++;		cl = cl.getComponentType();	    }	    StringBuffer sb = new StringBuffer();	    for (int i = 0; i < dimensions; i++) {		sb.append("[");	    }	    sb.append(getSignature(cl));	    type = sb.toString();	} else if (clazz.isPrimitive()) {	    if (clazz == Integer.TYPE) {		type = "I";	    } else if (clazz == Byte.TYPE) {		type = "B";	    } else if (clazz == Long.TYPE) {		type = "J";	    } else if (clazz == Float.TYPE) {		type = "F";	    } else if (clazz == Double.TYPE) {		type = "D";	    } else if (clazz == Short.TYPE) {		type = "S";	    } else if (clazz == Character.TYPE) {		type = "C";	    } else if (clazz == Boolean.TYPE) {		type = "Z";	    } else if (clazz == Void.TYPE) {		type = "V";	    }	} else {	    type = "L" + clazz.getName().replace('.', '/') + ";";	}	return type;    }    /*     * Compute the JVM method descriptor for the method.     */    static String getSignature(Method meth) {	StringBuffer sb = new StringBuffer();	sb.append("(");	Class[] params = meth.getParameterTypes(); // avoid clone	for (int j = 0; j < params.length; j++) {	    sb.append(getSignature(params[j]));	}	sb.append(")");	sb.append(getSignature(meth.getReturnType()));	return sb.toString();    }    /*     * Compute the JVM constructor descriptor for the constructor.     */    static String getSignature(Constructor cons) {	StringBuffer sb = new StringBuffer();	sb.append("(");	Class[] params = cons.getParameterTypes(); // avoid clone	for (int j = 0; j < params.length; j++) {	    sb.append(getSignature(params[j]));	}	sb.append(")V");	return sb.toString();    }    static private SoftCache descriptorFor = new SoftCache() ;    private static Field[] getDeclaredFields(final Class clz) {        return (Field[]) AccessController.doPrivileged(new PrivilegedAction() {            public Object run() {                return clz.getDeclaredFields();            }        });    }    /*     * The name of this descriptor     */    private String name;    /*     * The descriptor of the supertype.     */    private ObjectStreamClass superclass;    /*     * Flags for Serializable and Externalizable.     */    private boolean serializable;    private boolean externalizable;    /*     * Array of persistent fields of this class, sorted by     * type and name.     */    private ObjectStreamField[] fields;    /*     * Class that is a descriptor for in this virtual machine.     */    private Class ofClass;    /*     * True if descriptor for a proxy class.     */    boolean forProxyClass;    /*     * SerialVersionUID for this class.     */    private long suid = kDefaultUID;    private String suidStr = null;    /*     * Actual (computed) SerialVersionUID for this class.     */    private long actualSuid = kDefaultUID;    private String actualSuidStr = null;    /*     * The total number of bytes of primitive fields.     * The total number of object fields.     */    int primBytes;    int objFields;    /**     * Flag indicating whether or not this instance has      * successfully completed initialization.  This is to     * try to fix bug 4373844.  Working to move to     * reusing java.io.ObjectStreamClass for JDK 1.5.     */    private boolean initialized = false;    /* Internal lock object. */    private Object lock = new Object();    /* In JDK 1.1, external data was not written in block mode.     * As of JDK 1.2, external data is written in block data mode. This     * flag enables JDK 1.2 to be able to read JDK 1.1 written external data.     *     * @since JDK 1.2     */    private boolean hasExternalizableBlockData;    Method writeObjectMethod;    Method readObjectMethod;    private Method writeReplaceObjectMethod;    private Method readResolveObjectMethod;    private Constructor cons ;    /**     * Beginning in Java to IDL ptc/02-01-12, RMI-IIOP has a     * stream format version 2 which puts a fake valuetype around     * a Serializable's optional custom data.  This valuetype has     * a special repository ID made from the Serializable's     * information which we are pre-computing and     * storing here.     */    private String rmiiiopOptionalDataRepId = null;    /*     * ObjectStreamClass that this one was built from.     */    private ObjectStreamClass localClassDesc;    /* Find out if the class has a static class initializer <clinit> */    private static Method hasStaticInitializerMethod = null;    /**     * Returns true if the given class defines a static initializer method,     * false otherwise.     */    private static boolean hasStaticInitializer(Class cl) {        if (hasStaticInitializerMethod == null) {            Class classWithThisMethod = null;                        try {                try {                    // When using rip-int with Merlin or when this is a Merlin                    // workspace, the method we want is in sun.misc.ClassReflector                    // and absent from java.io.ObjectStreamClass.                    //                    // When compiling rip-int with JDK 1.3.x, we have to get it                    // from java.io.ObjectStreamClass.                    classWithThisMethod = Class.forName("sun.misc.ClassReflector");                } catch (ClassNotFoundException cnfe) {                    // Do nothing.  This is either not a Merlin workspace,                    // or rip-int is being compiled with something other than                    // Merlin, probably JDK 1.3.  Fall back on java.io.ObjectStreaClass.                }                if (classWithThisMethod == null)                    classWithThisMethod = java.io.ObjectStreamClass.class;                                hasStaticInitializerMethod =                    classWithThisMethod.getDeclaredMethod("hasStaticInitializer",                                                          new Class[] { Class.class });            } catch (NoSuchMethodException ex) {            }                        if (hasStaticInitializerMethod == null) {		// XXX I18N, logging needed                throw new InternalError("Can't find hasStaticInitializer method on "                                        + classWithThisMethod.getName());            }            hasStaticInitializerMethod.setAccessible(true);        }        try {            Boolean retval = (Boolean)                hasStaticInitializerMethod.invoke(null, new Object[] { cl });            return retval.booleanValue();        } catch (Exception ex) {	    // XXX I18N, logging needed            InternalError ie = new InternalError( "Error invoking hasStaticInitializer" ) ;	    ie.initCause( ex ) ;	    throw ie ;        }    }    /* The Class Object for java.io.Serializable */    private static Class classSerializable = null;    private static Class classExternalizable = null;    /*     * Resolve java.io.Serializable at load time.     */    static {	try {	    classSerializable = Class.forName("java.io.Serializable");	    classExternalizable = Class.forName("java.io.Externalizable");	} catch (Throwable e) {	    System.err.println("Could not load java.io.Serializable or java.io.Externalizable.");	}    }    /** use serialVersionUID from JDK 1.1. for interoperability */    private static final long serialVersionUID = -6120832682080437368L;    /**     * Set serialPersistentFields of a Serializable class to this value to     * denote that the class has no Serializable fields.     */    public static final ObjectStreamField[] NO_FIELDS =        new ObjectStreamField[0];    /*     * Entries held in the Cache of known ObjectStreamClass objects.     * Entries are chained together with the same hash value (modulo array size).     */    private static class ObjectStreamClassEntry // extends java.lang.ref.SoftReference    {	ObjectStreamClassEntry(ObjectStreamClass c) {	    //super(c);	    this.c = c;	}	ObjectStreamClassEntry next;	public Object get()	{	    return c;	}	private ObjectStreamClass c;    }    /*     * Comparator object for Classes and Interfaces     */    private static Comparator compareClassByName =    	new CompareClassByName();    private static class CompareClassByName implements Comparator {	public int compare(Object o1, Object o2) {	    Class c1 = (Class)o1;	    Class c2 = (Class)o2;	    return (c1.getName()).compareTo(c2.getName());	}    }    /**     * Comparator for ObjectStreamFields by name     */    private final static Comparator compareObjStrFieldsByName        = new CompareObjStrFieldsByName();    private static class CompareObjStrFieldsByName implements Comparator {        public int compare(Object o1, Object o2) {            ObjectStreamField osf1 = (ObjectStreamField)o1;            ObjectStreamField osf2 = (ObjectStreamField)o2;            return osf1.getName().compareTo(osf2.getName());        }    }    /*     * Comparator object for Members, Fields, and Methods     */    private static Comparator compareMemberByName =    	new CompareMemberByName();    private static class CompareMemberByName implements Comparator {	public int compare(Object o1, Object o2) {	    String s1 = ((Member)o1).getName();	    String s2 = ((Member)o2).getName();	    if (o1 instanceof Method) {		s1 += getSignature((Method)o1);		s2 += getSignature((Method)o2);	    } else if (o1 instanceof Constructor) {		s1 += getSignature((Constructor)o1);		s2 += getSignature((Constructor)o2);	    }	    return s1.compareTo(s2);	}    }    /* It is expensive to recompute a method or constructor signature       many times, so compute it only once using this data structure. */    private static class MethodSignature implements Comparator {	Member member;	String signature;      // cached parameter signature	/* Given an array of Method or Constructor members,	   return a sorted array of the non-private members.*/	/* A better implementation would be to implement the returned data	   structure as an insertion sorted link list.*/	static MethodSignature[] removePrivateAndSort(Member[] m) {	    int numNonPrivate = 0;	    for (int i = 0; i < m.length; i++) {		if (! Modifier.isPrivate(m[i].getModifiers())) {		    numNonPrivate++;		}	    }	    MethodSignature[] cm = new MethodSignature[numNonPrivate];	    int cmi = 0;	    for (int i = 0; i < m.length; i++) {		if (! Modifier.isPrivate(m[i].getModifiers())) {		    cm[cmi] = new MethodSignature(m[i]);		    cmi++;		}	    }	    if (cmi > 0)		Arrays.sort(cm, cm[0]);	    return cm;	}	/* Assumes that o1 and o2 are either both methods	   or both constructors.*/	public int compare(Object o1, Object o2) {	    /* Arrays.sort calls compare when o1 and o2 are equal.*/	    if (o1 == o2)		return 0;	    MethodSignature c1 = (MethodSignature)o1;	    MethodSignature c2 = (MethodSignature)o2;	    int result;	    if (isConstructor()) {		result = c1.signature.compareTo(c2.signature);	    } else { // is a Method.		result = c1.member.getName().compareTo(c2.member.getName());		if (result == 0)		    result = c1.signature.compareTo(c2.signature);	    }	    return result;	}	final private boolean isConstructor() {	    return member instanceof Constructor;	}	private MethodSignature(Member m) {	    member = m;	    if (isConstructor()) {		signature = ObjectStreamClass.getSignature((Constructor)m);	    } else {		signature = ObjectStreamClass.getSignature((Method)m);	    }	}    }    /**     * Returns non-static, non-abstract method with given signature provided it     * is defined by or accessible (via inheritance) by the given class, or     * null if no match found.  Access checks are disabled on the returned     * method (if any).     *     * Copied from the Merlin java.io.ObjectStreamClass.     */    private static Method getInheritableMethod(Class cl, String name,					       Class[] argTypes,					       Class returnType)    {	Method meth = null;	Class defCl = cl;	while (defCl != null) {	    try {		meth = defCl.getDeclaredMethod(name, argTypes);		break;	    } catch (NoSuchMethodException ex) {		defCl = defCl.getSuperclass();	    }	}	if ((meth == null) || (meth.getReturnType() != returnType)) {	    return null;	}	meth.setAccessible(true);	int mods = meth.getModifiers();	if ((mods & (Modifier.STATIC | Modifier.ABSTRACT)) != 0) {	    return null;	} else if ((mods & (Modifier.PUBLIC | Modifier.PROTECTED)) != 0) {	    return meth;	} else if ((mods & Modifier.PRIVATE) != 0) {	    return (cl == defCl) ? meth : null;	} else {	    return packageEquals(cl, defCl) ? meth : null;	}    }    /**     * Returns true if classes are defined in the same package, false     * otherwise.     *     * Copied from the Merlin java.io.ObjectStreamClass.     */    private static boolean packageEquals(Class cl1, Class cl2) {	Package pkg1 = cl1.getPackage(), pkg2 = cl2.getPackage();	return ((pkg1 == pkg2) || ((pkg1 != null) && (pkg1.equals(pkg2))));    }}

⌨️ 快捷键说明

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