0N/A/*
2362N/A * Copyright (c) 1996, 2011, Oracle and/or its affiliates. All rights reserved.
0N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
0N/A *
0N/A * This code is free software; you can redistribute it and/or modify it
0N/A * under the terms of the GNU General Public License version 2 only, as
2362N/A * published by the Free Software Foundation. Oracle designates this
0N/A * particular file as subject to the "Classpath" exception as provided
2362N/A * by Oracle in the LICENSE file that accompanied this code.
0N/A *
0N/A * This code is distributed in the hope that it will be useful, but WITHOUT
0N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
0N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
0N/A * version 2 for more details (a copy is included in the LICENSE file that
0N/A * accompanied this code).
0N/A *
0N/A * You should have received a copy of the GNU General Public License version
0N/A * 2 along with this work; if not, write to the Free Software Foundation,
0N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
0N/A *
2362N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
2362N/A * or visit www.oracle.com if you need additional information or have any
2362N/A * questions.
0N/A */
0N/A
0N/Apackage java.io;
0N/A
0N/Aimport java.lang.ref.Reference;
243N/Aimport java.lang.ref.ReferenceQueue;
0N/Aimport java.lang.ref.SoftReference;
0N/Aimport java.lang.ref.WeakReference;
0N/Aimport java.lang.reflect.Constructor;
0N/Aimport java.lang.reflect.Field;
0N/Aimport java.lang.reflect.InvocationTargetException;
0N/Aimport java.lang.reflect.Member;
0N/Aimport java.lang.reflect.Method;
0N/Aimport java.lang.reflect.Modifier;
0N/Aimport java.lang.reflect.Proxy;
0N/Aimport java.security.AccessController;
0N/Aimport java.security.MessageDigest;
0N/Aimport java.security.NoSuchAlgorithmException;
0N/Aimport java.security.PrivilegedAction;
0N/Aimport java.util.ArrayList;
0N/Aimport java.util.Arrays;
0N/Aimport java.util.Collections;
0N/Aimport java.util.Comparator;
0N/Aimport java.util.HashSet;
0N/Aimport java.util.Set;
0N/Aimport java.util.concurrent.ConcurrentHashMap;
0N/Aimport java.util.concurrent.ConcurrentMap;
0N/Aimport sun.misc.Unsafe;
0N/Aimport sun.reflect.CallerSensitive;
0N/Aimport sun.reflect.Reflection;
0N/Aimport sun.reflect.ReflectionFactory;
0N/Aimport sun.reflect.misc.ReflectUtil;
0N/A
0N/A/**
0N/A * Serialization's descriptor for classes. It contains the name and
0N/A * serialVersionUID of the class. The ObjectStreamClass for a specific class
0N/A * loaded in this Java VM can be found/created using the lookup method.
0N/A *
0N/A * <p>The algorithm to compute the SerialVersionUID is described in
0N/A * <a href="../../../platform/serialization/spec/class.html#4100">Object
0N/A * Serialization Specification, Section 4.6, Stream Unique Identifiers</a>.
0N/A *
0N/A * @author Mike Warres
0N/A * @author Roger Riggs
0N/A * @see ObjectStreamField
0N/A * @see <a href="../../../platform/serialization/spec/class.html">Object Serialization Specification, Section 4, Class Descriptors</a>
0N/A * @since JDK1.1
0N/A */
0N/Apublic class ObjectStreamClass implements Serializable {
0N/A
0N/A /** serialPersistentFields value indicating no serializable fields */
0N/A public static final ObjectStreamField[] NO_FIELDS =
0N/A new ObjectStreamField[0];
0N/A
0N/A private static final long serialVersionUID = -6120832682080437368L;
0N/A private static final ObjectStreamField[] serialPersistentFields =
0N/A NO_FIELDS;
0N/A
0N/A /** reflection factory for obtaining serialization constructors */
0N/A private static final ReflectionFactory reflFactory =
0N/A AccessController.doPrivileged(
0N/A new ReflectionFactory.GetReflectionFactoryAction());
0N/A
0N/A private static class Caches {
0N/A /** cache mapping local classes -> descriptors */
0N/A static final ConcurrentMap<WeakClassKey,Reference<?>> localDescs =
0N/A new ConcurrentHashMap<>();
0N/A
0N/A /** cache mapping field group/local desc pairs -> field reflectors */
0N/A static final ConcurrentMap<FieldReflectorKey,Reference<?>> reflectors =
0N/A new ConcurrentHashMap<>();
0N/A
0N/A /** queue for WeakReferences to local classes */
0N/A private static final ReferenceQueue<Class<?>> localDescsQueue =
0N/A new ReferenceQueue<>();
0N/A /** queue for WeakReferences to field reflectors keys */
0N/A private static final ReferenceQueue<Class<?>> reflectorsQueue =
0N/A new ReferenceQueue<>();
0N/A }
0N/A
0N/A /** class associated with this descriptor (if any) */
0N/A private Class<?> cl;
0N/A /** name of class represented by this descriptor */
0N/A private String name;
0N/A /** serialVersionUID of represented class (null if not computed yet) */
0N/A private volatile Long suid;
0N/A
0N/A /** true if represents dynamic proxy class */
0N/A private boolean isProxy;
0N/A /** true if represents enum type */
0N/A private boolean isEnum;
0N/A /** true if represented class implements Serializable */
0N/A private boolean serializable;
0N/A /** true if represented class implements Externalizable */
0N/A private boolean externalizable;
0N/A /** true if desc has data written by class-defined writeObject method */
0N/A private boolean hasWriteObjectData;
0N/A /**
0N/A * true if desc has externalizable data written in block data format; this
0N/A * must be true by default to accommodate ObjectInputStream subclasses which
0N/A * override readClassDescriptor() to return class descriptors obtained from
0N/A * ObjectStreamClass.lookup() (see 4461737)
0N/A */
0N/A private boolean hasBlockExternalData = true;
0N/A
0N/A /**
0N/A * Contains information about InvalidClassException instances to be thrown
0N/A * when attempting operations on an invalid class. Note that instances of
0N/A * this class are immutable and are potentially shared among
0N/A * ObjectStreamClass instances.
0N/A */
0N/A private static class ExceptionInfo {
0N/A private final String className;
0N/A private final String message;
0N/A
0N/A ExceptionInfo(String cn, String msg) {
0N/A className = cn;
0N/A message = msg;
0N/A }
0N/A
0N/A /**
0N/A * Returns (does not throw) an InvalidClassException instance created
0N/A * from the information in this object, suitable for being thrown by
0N/A * the caller.
0N/A */
0N/A InvalidClassException newInvalidClassException() {
0N/A return new InvalidClassException(className, message);
0N/A }
0N/A }
0N/A
0N/A /** exception (if any) thrown while attempting to resolve class */
0N/A private ClassNotFoundException resolveEx;
0N/A /** exception (if any) to throw if non-enum deserialization attempted */
0N/A private ExceptionInfo deserializeEx;
0N/A /** exception (if any) to throw if non-enum serialization attempted */
0N/A private ExceptionInfo serializeEx;
0N/A /** exception (if any) to throw if default serialization attempted */
0N/A private ExceptionInfo defaultSerializeEx;
0N/A
0N/A /** serializable fields */
0N/A private ObjectStreamField[] fields;
0N/A /** aggregate marshalled size of primitive fields */
0N/A private int primDataSize;
0N/A /** number of non-primitive fields */
0N/A private int numObjFields;
0N/A /** reflector for setting/getting serializable field values */
0N/A private FieldReflector fieldRefl;
0N/A /** data layout of serialized objects described by this class desc */
0N/A private volatile ClassDataSlot[] dataLayout;
0N/A
0N/A /** serialization-appropriate constructor, or null if none */
0N/A private Constructor cons;
0N/A /** class-defined writeObject method, or null if none */
0N/A private Method writeObjectMethod;
0N/A /** class-defined readObject method, or null if none */
0N/A private Method readObjectMethod;
0N/A /** class-defined readObjectNoData method, or null if none */
0N/A private Method readObjectNoDataMethod;
0N/A /** class-defined writeReplace method, or null if none */
0N/A private Method writeReplaceMethod;
0N/A /** class-defined readResolve method, or null if none */
0N/A private Method readResolveMethod;
0N/A
0N/A /** local class descriptor for represented class (may point to self) */
0N/A private ObjectStreamClass localDesc;
0N/A /** superclass descriptor appearing in stream */
0N/A private ObjectStreamClass superDesc;
0N/A
0N/A /**
0N/A * Initializes native code.
0N/A */
0N/A private static native void initNative();
0N/A static {
0N/A initNative();
0N/A }
0N/A
0N/A /**
0N/A * Find the descriptor for a class that can be serialized. Creates an
0N/A * ObjectStreamClass instance if one does not exist yet for class. Null is
0N/A * returned if the specified class does not implement java.io.Serializable
0N/A * or java.io.Externalizable.
0N/A *
0N/A * @param cl class for which to get the descriptor
0N/A * @return the class descriptor for the specified class
0N/A */
0N/A public static ObjectStreamClass lookup(Class<?> cl) {
0N/A return lookup(cl, false);
0N/A }
0N/A
0N/A /**
0N/A * Returns the descriptor for any class, regardless of whether it
0N/A * implements {@link Serializable}.
0N/A *
0N/A * @param cl class for which to get the descriptor
0N/A * @return the class descriptor for the specified class
0N/A * @since 1.6
0N/A */
0N/A public static ObjectStreamClass lookupAny(Class<?> cl) {
0N/A return lookup(cl, true);
0N/A }
0N/A
0N/A /**
0N/A * Returns the name of the class described by this descriptor.
0N/A * This method returns the name of the class in the format that
0N/A * is used by the {@link Class#getName} method.
0N/A *
0N/A * @return a string representing the name of the class
0N/A */
0N/A public String getName() {
0N/A return name;
0N/A }
0N/A
0N/A /**
0N/A * Return the serialVersionUID for this class. The serialVersionUID
0N/A * defines a set of classes all with the same name that have evolved from a
0N/A * common root class and agree to be serialized and deserialized using a
0N/A * common format. NonSerializable classes have a serialVersionUID of 0L.
0N/A *
0N/A * @return the SUID of the class described by this descriptor
0N/A */
0N/A public long getSerialVersionUID() {
0N/A // REMIND: synchronize instead of relying on volatile?
0N/A if (suid == null) {
0N/A suid = AccessController.doPrivileged(
0N/A new PrivilegedAction<Long>() {
0N/A public Long run() {
0N/A return computeDefaultSUID(cl);
0N/A }
0N/A }
0N/A );
0N/A }
0N/A return suid.longValue();
0N/A }
0N/A
0N/A /**
0N/A * Return the class in the local VM that this version is mapped to. Null
0N/A * is returned if there is no corresponding local class.
0N/A *
0N/A * @return the <code>Class</code> instance that this descriptor represents
0N/A */
0N/A @CallerSensitive
0N/A public Class<?> forClass() {
0N/A if (cl == null) {
0N/A return null;
0N/A }
0N/A if (System.getSecurityManager() != null) {
0N/A Class<?> caller = Reflection.getCallerClass();
0N/A if (ReflectUtil.needsPackageAccessCheck(caller.getClassLoader(), cl.getClassLoader())) {
0N/A ReflectUtil.checkPackageAccess(cl);
0N/A }
0N/A }
0N/A return cl;
0N/A }
0N/A
0N/A /**
0N/A * Return an array of the fields of this serializable class.
0N/A *
0N/A * @return an array containing an element for each persistent field of
0N/A * this class. Returns an array of length zero if there are no
0N/A * fields.
0N/A * @since 1.2
0N/A */
0N/A public ObjectStreamField[] getFields() {
0N/A return getFields(true);
0N/A }
0N/A
0N/A /**
0N/A * Get the field of this class by name.
0N/A *
0N/A * @param name the name of the data field to look for
0N/A * @return The ObjectStreamField object of the named field or null if
0N/A * there is no such named field.
0N/A */
0N/A public ObjectStreamField getField(String name) {
0N/A return getField(name, null);
0N/A }
0N/A
0N/A /**
0N/A * Return a string describing this ObjectStreamClass.
0N/A */
0N/A public String toString() {
0N/A return name + ": static final long serialVersionUID = " +
0N/A getSerialVersionUID() + "L;";
0N/A }
0N/A
0N/A /**
0N/A * Looks up and returns class descriptor for given class, or null if class
0N/A * is non-serializable and "all" is set to false.
243N/A *
0N/A * @param cl class to look up
0N/A * @param all if true, return descriptors for all classes; if false, only
0N/A * return descriptors for serializable classes
0N/A */
0N/A static ObjectStreamClass lookup(Class<?> cl, boolean all) {
0N/A if (!(all || Serializable.class.isAssignableFrom(cl))) {
0N/A return null;
0N/A }
0N/A processQueue(Caches.localDescsQueue, Caches.localDescs);
0N/A WeakClassKey key = new WeakClassKey(cl, Caches.localDescsQueue);
0N/A Reference<?> ref = Caches.localDescs.get(key);
0N/A Object entry = null;
0N/A if (ref != null) {
0N/A entry = ref.get();
0N/A }
0N/A EntryFuture future = null;
0N/A if (entry == null) {
0N/A EntryFuture newEntry = new EntryFuture();
0N/A Reference<?> newRef = new SoftReference<>(newEntry);
0N/A do {
0N/A if (ref != null) {
0N/A Caches.localDescs.remove(key, ref);
0N/A }
0N/A ref = Caches.localDescs.putIfAbsent(key, newRef);
0N/A if (ref != null) {
0N/A entry = ref.get();
0N/A }
0N/A } while (ref != null && entry == null);
0N/A if (entry == null) {
0N/A future = newEntry;
0N/A }
0N/A }
0N/A
0N/A if (entry instanceof ObjectStreamClass) { // check common case first
0N/A return (ObjectStreamClass) entry;
0N/A }
0N/A if (entry instanceof EntryFuture) {
0N/A future = (EntryFuture) entry;
0N/A if (future.getOwner() == Thread.currentThread()) {
0N/A /*
0N/A * Handle nested call situation described by 4803747: waiting
0N/A * for future value to be set by a lookup() call further up the
0N/A * stack will result in deadlock, so calculate and set the
0N/A * future value here instead.
0N/A */
0N/A entry = null;
0N/A } else {
0N/A entry = future.get();
0N/A }
0N/A }
0N/A if (entry == null) {
0N/A try {
0N/A entry = new ObjectStreamClass(cl);
0N/A } catch (Throwable th) {
0N/A entry = th;
0N/A }
0N/A if (future.set(entry)) {
0N/A Caches.localDescs.put(key, new SoftReference<Object>(entry));
0N/A } else {
0N/A // nested lookup call already set future
0N/A entry = future.get();
0N/A }
0N/A }
0N/A
0N/A if (entry instanceof ObjectStreamClass) {
0N/A return (ObjectStreamClass) entry;
0N/A } else if (entry instanceof RuntimeException) {
0N/A throw (RuntimeException) entry;
0N/A } else if (entry instanceof Error) {
0N/A throw (Error) entry;
0N/A } else {
0N/A throw new InternalError("unexpected entry: " + entry);
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Placeholder used in class descriptor and field reflector lookup tables
0N/A * for an entry in the process of being initialized. (Internal) callers
0N/A * which receive an EntryFuture belonging to another thread as the result
0N/A * of a lookup should call the get() method of the EntryFuture; this will
0N/A * return the actual entry once it is ready for use and has been set(). To
0N/A * conserve objects, EntryFutures synchronize on themselves.
0N/A */
0N/A private static class EntryFuture {
0N/A
0N/A private static final Object unset = new Object();
0N/A private final Thread owner = Thread.currentThread();
0N/A private Object entry = unset;
0N/A
0N/A /**
0N/A * Attempts to set the value contained by this EntryFuture. If the
0N/A * EntryFuture's value has not been set already, then the value is
0N/A * saved, any callers blocked in the get() method are notified, and
0N/A * true is returned. If the value has already been set, then no saving
0N/A * or notification occurs, and false is returned.
0N/A */
0N/A synchronized boolean set(Object entry) {
0N/A if (this.entry != unset) {
0N/A return false;
0N/A }
0N/A this.entry = entry;
0N/A notifyAll();
0N/A return true;
0N/A }
0N/A
0N/A /**
0N/A * Returns the value contained by this EntryFuture, blocking if
0N/A * necessary until a value is set.
0N/A */
0N/A synchronized Object get() {
0N/A boolean interrupted = false;
0N/A while (entry == unset) {
0N/A try {
0N/A wait();
0N/A } catch (InterruptedException ex) {
0N/A interrupted = true;
0N/A }
0N/A }
0N/A if (interrupted) {
0N/A AccessController.doPrivileged(
0N/A new PrivilegedAction<Void>() {
0N/A public Void run() {
0N/A Thread.currentThread().interrupt();
0N/A return null;
0N/A }
0N/A }
0N/A );
0N/A }
0N/A return entry;
0N/A }
0N/A
0N/A /**
0N/A * Returns the thread that created this EntryFuture.
0N/A */
0N/A Thread getOwner() {
0N/A return owner;
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Creates local class descriptor representing given class.
0N/A */
0N/A private ObjectStreamClass(final Class<?> cl) {
0N/A this.cl = cl;
0N/A name = cl.getName();
0N/A isProxy = Proxy.isProxyClass(cl);
0N/A isEnum = Enum.class.isAssignableFrom(cl);
0N/A serializable = Serializable.class.isAssignableFrom(cl);
0N/A externalizable = Externalizable.class.isAssignableFrom(cl);
0N/A
0N/A Class<?> superCl = cl.getSuperclass();
0N/A superDesc = (superCl != null) ? lookup(superCl, false) : null;
0N/A localDesc = this;
0N/A
0N/A if (serializable) {
0N/A AccessController.doPrivileged(new PrivilegedAction<Void>() {
0N/A public Void run() {
0N/A if (isEnum) {
0N/A suid = Long.valueOf(0);
0N/A fields = NO_FIELDS;
0N/A return null;
0N/A }
0N/A if (cl.isArray()) {
0N/A fields = NO_FIELDS;
0N/A return null;
0N/A }
0N/A
0N/A suid = getDeclaredSUID(cl);
0N/A try {
0N/A fields = getSerialFields(cl);
0N/A computeFieldOffsets();
0N/A } catch (InvalidClassException e) {
0N/A serializeEx = deserializeEx =
0N/A new ExceptionInfo(e.classname, e.getMessage());
0N/A fields = NO_FIELDS;
0N/A }
0N/A
0N/A if (externalizable) {
0N/A cons = getExternalizableConstructor(cl);
0N/A } else {
0N/A cons = getSerializableConstructor(cl);
0N/A writeObjectMethod = getPrivateMethod(cl, "writeObject",
0N/A new Class<?>[] { ObjectOutputStream.class },
0N/A Void.TYPE);
0N/A readObjectMethod = getPrivateMethod(cl, "readObject",
0N/A new Class<?>[] { ObjectInputStream.class },
0N/A Void.TYPE);
0N/A readObjectNoDataMethod = getPrivateMethod(
0N/A cl, "readObjectNoData", null, Void.TYPE);
0N/A hasWriteObjectData = (writeObjectMethod != null);
0N/A }
0N/A writeReplaceMethod = getInheritableMethod(
0N/A cl, "writeReplace", null, Object.class);
0N/A readResolveMethod = getInheritableMethod(
0N/A cl, "readResolve", null, Object.class);
0N/A return null;
0N/A }
0N/A });
0N/A } else {
0N/A suid = Long.valueOf(0);
0N/A fields = NO_FIELDS;
0N/A }
0N/A
0N/A try {
0N/A fieldRefl = getReflector(fields, this);
0N/A } catch (InvalidClassException ex) {
0N/A // field mismatches impossible when matching local fields vs. self
0N/A throw new InternalError();
0N/A }
0N/A
0N/A if (deserializeEx == null) {
0N/A if (isEnum) {
0N/A deserializeEx = new ExceptionInfo(name, "enum type");
0N/A } else if (cons == null) {
0N/A deserializeEx = new ExceptionInfo(name, "no valid constructor");
0N/A }
0N/A }
0N/A for (int i = 0; i < fields.length; i++) {
0N/A if (fields[i].getField() == null) {
0N/A defaultSerializeEx = new ExceptionInfo(
0N/A name, "unmatched serializable field(s) declared");
0N/A }
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Creates blank class descriptor which should be initialized via a
0N/A * subsequent call to initProxy(), initNonProxy() or readNonProxy().
0N/A */
0N/A ObjectStreamClass() {
0N/A }
0N/A
0N/A /**
0N/A * Initializes class descriptor representing a proxy class.
0N/A */
0N/A void initProxy(Class<?> cl,
0N/A ClassNotFoundException resolveEx,
0N/A ObjectStreamClass superDesc)
0N/A throws InvalidClassException
0N/A {
0N/A this.cl = cl;
0N/A this.resolveEx = resolveEx;
0N/A this.superDesc = superDesc;
0N/A isProxy = true;
0N/A serializable = true;
0N/A suid = Long.valueOf(0);
0N/A fields = NO_FIELDS;
0N/A
0N/A if (cl != null) {
0N/A localDesc = lookup(cl, true);
0N/A if (!localDesc.isProxy) {
0N/A throw new InvalidClassException(
0N/A "cannot bind proxy descriptor to a non-proxy class");
0N/A }
0N/A name = localDesc.name;
0N/A externalizable = localDesc.externalizable;
0N/A cons = localDesc.cons;
0N/A writeReplaceMethod = localDesc.writeReplaceMethod;
0N/A readResolveMethod = localDesc.readResolveMethod;
0N/A deserializeEx = localDesc.deserializeEx;
0N/A }
0N/A fieldRefl = getReflector(fields, localDesc);
0N/A }
0N/A
0N/A /**
0N/A * Initializes class descriptor representing a non-proxy class.
0N/A */
0N/A void initNonProxy(ObjectStreamClass model,
0N/A Class<?> cl,
0N/A ClassNotFoundException resolveEx,
0N/A ObjectStreamClass superDesc)
0N/A throws InvalidClassException
0N/A {
0N/A this.cl = cl;
0N/A this.resolveEx = resolveEx;
0N/A this.superDesc = superDesc;
0N/A name = model.name;
0N/A suid = Long.valueOf(model.getSerialVersionUID());
0N/A isProxy = false;
0N/A isEnum = model.isEnum;
0N/A serializable = model.serializable;
0N/A externalizable = model.externalizable;
0N/A hasBlockExternalData = model.hasBlockExternalData;
0N/A hasWriteObjectData = model.hasWriteObjectData;
0N/A fields = model.fields;
0N/A primDataSize = model.primDataSize;
0N/A numObjFields = model.numObjFields;
0N/A
0N/A if (cl != null) {
0N/A localDesc = lookup(cl, true);
0N/A if (localDesc.isProxy) {
0N/A throw new InvalidClassException(
0N/A "cannot bind non-proxy descriptor to a proxy class");
0N/A }
0N/A if (isEnum != localDesc.isEnum) {
0N/A throw new InvalidClassException(isEnum ?
0N/A "cannot bind enum descriptor to a non-enum class" :
0N/A "cannot bind non-enum descriptor to an enum class");
0N/A }
0N/A
0N/A if (serializable == localDesc.serializable &&
0N/A !cl.isArray() &&
0N/A suid.longValue() != localDesc.getSerialVersionUID())
0N/A {
0N/A throw new InvalidClassException(localDesc.name,
0N/A "local class incompatible: " +
0N/A "stream classdesc serialVersionUID = " + suid +
0N/A ", local class serialVersionUID = " +
0N/A localDesc.getSerialVersionUID());
0N/A }
0N/A
0N/A if (!classNamesEqual(name, localDesc.name)) {
0N/A throw new InvalidClassException(localDesc.name,
0N/A "local class name incompatible with stream class " +
0N/A "name \"" + name + "\"");
0N/A }
0N/A
0N/A if (!isEnum) {
0N/A if ((serializable == localDesc.serializable) &&
0N/A (externalizable != localDesc.externalizable))
0N/A {
0N/A throw new InvalidClassException(localDesc.name,
0N/A "Serializable incompatible with Externalizable");
0N/A }
0N/A
0N/A if ((serializable != localDesc.serializable) ||
0N/A (externalizable != localDesc.externalizable) ||
0N/A !(serializable || externalizable))
0N/A {
0N/A deserializeEx = new ExceptionInfo(
0N/A localDesc.name, "class invalid for deserialization");
0N/A }
0N/A }
0N/A
0N/A cons = localDesc.cons;
0N/A writeObjectMethod = localDesc.writeObjectMethod;
0N/A readObjectMethod = localDesc.readObjectMethod;
0N/A readObjectNoDataMethod = localDesc.readObjectNoDataMethod;
0N/A writeReplaceMethod = localDesc.writeReplaceMethod;
0N/A readResolveMethod = localDesc.readResolveMethod;
0N/A if (deserializeEx == null) {
0N/A deserializeEx = localDesc.deserializeEx;
0N/A }
0N/A }
0N/A fieldRefl = getReflector(fields, localDesc);
0N/A // reassign to matched fields so as to reflect local unshared settings
0N/A fields = fieldRefl.getFields();
0N/A }
0N/A
0N/A /**
0N/A * Reads non-proxy class descriptor information from given input stream.
0N/A * The resulting class descriptor is not fully functional; it can only be
0N/A * used as input to the ObjectInputStream.resolveClass() and
0N/A * ObjectStreamClass.initNonProxy() methods.
0N/A */
0N/A void readNonProxy(ObjectInputStream in)
0N/A throws IOException, ClassNotFoundException
0N/A {
0N/A name = in.readUTF();
0N/A suid = Long.valueOf(in.readLong());
0N/A isProxy = false;
0N/A
0N/A byte flags = in.readByte();
0N/A hasWriteObjectData =
0N/A ((flags & ObjectStreamConstants.SC_WRITE_METHOD) != 0);
0N/A hasBlockExternalData =
0N/A ((flags & ObjectStreamConstants.SC_BLOCK_DATA) != 0);
0N/A externalizable =
0N/A ((flags & ObjectStreamConstants.SC_EXTERNALIZABLE) != 0);
0N/A boolean sflag =
0N/A ((flags & ObjectStreamConstants.SC_SERIALIZABLE) != 0);
0N/A if (externalizable && sflag) {
0N/A throw new InvalidClassException(
0N/A name, "serializable and externalizable flags conflict");
0N/A }
0N/A serializable = externalizable || sflag;
0N/A isEnum = ((flags & ObjectStreamConstants.SC_ENUM) != 0);
0N/A if (isEnum && suid.longValue() != 0L) {
0N/A throw new InvalidClassException(name,
0N/A "enum descriptor has non-zero serialVersionUID: " + suid);
0N/A }
0N/A
0N/A int numFields = in.readShort();
0N/A if (isEnum && numFields != 0) {
0N/A throw new InvalidClassException(name,
0N/A "enum descriptor has non-zero field count: " + numFields);
0N/A }
0N/A fields = (numFields > 0) ?
0N/A new ObjectStreamField[numFields] : NO_FIELDS;
0N/A for (int i = 0; i < numFields; i++) {
0N/A char tcode = (char) in.readByte();
0N/A String fname = in.readUTF();
0N/A String signature = ((tcode == 'L') || (tcode == '[')) ?
0N/A in.readTypeString() : new String(new char[] { tcode });
0N/A try {
0N/A fields[i] = new ObjectStreamField(fname, signature, false);
0N/A } catch (RuntimeException e) {
0N/A throw (IOException) new InvalidClassException(name,
0N/A "invalid descriptor for field " + fname).initCause(e);
0N/A }
0N/A }
0N/A computeFieldOffsets();
0N/A }
0N/A
0N/A /**
0N/A * Writes non-proxy class descriptor information to given output stream.
0N/A */
0N/A void writeNonProxy(ObjectOutputStream out) throws IOException {
0N/A out.writeUTF(name);
0N/A out.writeLong(getSerialVersionUID());
0N/A
0N/A byte flags = 0;
0N/A if (externalizable) {
0N/A flags |= ObjectStreamConstants.SC_EXTERNALIZABLE;
0N/A int protocol = out.getProtocolVersion();
0N/A if (protocol != ObjectStreamConstants.PROTOCOL_VERSION_1) {
0N/A flags |= ObjectStreamConstants.SC_BLOCK_DATA;
0N/A }
0N/A } else if (serializable) {
0N/A flags |= ObjectStreamConstants.SC_SERIALIZABLE;
0N/A }
0N/A if (hasWriteObjectData) {
0N/A flags |= ObjectStreamConstants.SC_WRITE_METHOD;
0N/A }
0N/A if (isEnum) {
0N/A flags |= ObjectStreamConstants.SC_ENUM;
0N/A }
0N/A out.writeByte(flags);
0N/A
0N/A out.writeShort(fields.length);
0N/A for (int i = 0; i < fields.length; i++) {
0N/A ObjectStreamField f = fields[i];
0N/A out.writeByte(f.getTypeCode());
0N/A out.writeUTF(f.getName());
0N/A if (!f.isPrimitive()) {
0N/A out.writeTypeString(f.getTypeString());
0N/A }
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Returns ClassNotFoundException (if any) thrown while attempting to
0N/A * resolve local class corresponding to this class descriptor.
0N/A */
0N/A ClassNotFoundException getResolveException() {
0N/A return resolveEx;
0N/A }
0N/A
0N/A /**
0N/A * Throws an InvalidClassException if object instances referencing this
0N/A * class descriptor should not be allowed to deserialize. This method does
0N/A * not apply to deserialization of enum constants.
0N/A */
0N/A void checkDeserialize() throws InvalidClassException {
0N/A if (deserializeEx != null) {
0N/A throw deserializeEx.newInvalidClassException();
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Throws an InvalidClassException if objects whose class is represented by
0N/A * this descriptor should not be allowed to serialize. This method does
0N/A * not apply to serialization of enum constants.
0N/A */
0N/A void checkSerialize() throws InvalidClassException {
0N/A if (serializeEx != null) {
0N/A throw serializeEx.newInvalidClassException();
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Throws an InvalidClassException if objects whose class is represented by
0N/A * this descriptor should not be permitted to use default serialization
0N/A * (e.g., if the class declares serializable fields that do not correspond
0N/A * to actual fields, and hence must use the GetField API). This method
0N/A * does not apply to deserialization of enum constants.
0N/A */
0N/A void checkDefaultSerialize() throws InvalidClassException {
0N/A if (defaultSerializeEx != null) {
0N/A throw defaultSerializeEx.newInvalidClassException();
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Returns superclass descriptor. Note that on the receiving side, the
0N/A * superclass descriptor may be bound to a class that is not a superclass
0N/A * of the subclass descriptor's bound class.
0N/A */
0N/A ObjectStreamClass getSuperDesc() {
0N/A return superDesc;
0N/A }
0N/A
0N/A /**
0N/A * Returns the "local" class descriptor for the class associated with this
0N/A * class descriptor (i.e., the result of
0N/A * ObjectStreamClass.lookup(this.forClass())) or null if there is no class
0N/A * associated with this descriptor.
0N/A */
0N/A ObjectStreamClass getLocalDesc() {
0N/A return localDesc;
0N/A }
0N/A
0N/A /**
0N/A * Returns arrays of ObjectStreamFields representing the serializable
0N/A * fields of the represented class. If copy is true, a clone of this class
0N/A * descriptor's field array is returned, otherwise the array itself is
0N/A * returned.
0N/A */
0N/A ObjectStreamField[] getFields(boolean copy) {
0N/A return copy ? fields.clone() : fields;
0N/A }
0N/A
0N/A /**
0N/A * Looks up a serializable field of the represented class by name and type.
0N/A * A specified type of null matches all types, Object.class matches all
0N/A * non-primitive types, and any other non-null type matches assignable
0N/A * types only. Returns matching field, or null if no match found.
0N/A */
0N/A ObjectStreamField getField(String name, Class<?> type) {
0N/A for (int i = 0; i < fields.length; i++) {
0N/A ObjectStreamField f = fields[i];
0N/A if (f.getName().equals(name)) {
0N/A if (type == null ||
0N/A (type == Object.class && !f.isPrimitive()))
0N/A {
0N/A return f;
0N/A }
0N/A Class<?> ftype = f.getType();
0N/A if (ftype != null && type.isAssignableFrom(ftype)) {
0N/A return f;
0N/A }
0N/A }
0N/A }
0N/A return null;
0N/A }
0N/A
0N/A /**
0N/A * Returns true if class descriptor represents a dynamic proxy class, false
0N/A * otherwise.
0N/A */
0N/A boolean isProxy() {
0N/A return isProxy;
0N/A }
0N/A
0N/A /**
0N/A * Returns true if class descriptor represents an enum type, false
0N/A * otherwise.
0N/A */
0N/A boolean isEnum() {
0N/A return isEnum;
0N/A }
0N/A
0N/A /**
0N/A * Returns true if represented class implements Externalizable, false
0N/A * otherwise.
0N/A */
0N/A boolean isExternalizable() {
0N/A return externalizable;
0N/A }
0N/A
0N/A /**
0N/A * Returns true if represented class implements Serializable, false
0N/A * otherwise.
0N/A */
0N/A boolean isSerializable() {
0N/A return serializable;
0N/A }
0N/A
0N/A /**
0N/A * Returns true if class descriptor represents externalizable class that
0N/A * has written its data in 1.2 (block data) format, false otherwise.
0N/A */
0N/A boolean hasBlockExternalData() {
0N/A return hasBlockExternalData;
0N/A }
0N/A
0N/A /**
0N/A * Returns true if class descriptor represents serializable (but not
0N/A * externalizable) class which has written its data via a custom
0N/A * writeObject() method, false otherwise.
0N/A */
0N/A boolean hasWriteObjectData() {
0N/A return hasWriteObjectData;
0N/A }
0N/A
0N/A /**
0N/A * Returns true if represented class is serializable/externalizable and can
0N/A * be instantiated by the serialization runtime--i.e., if it is
0N/A * externalizable and defines a public no-arg constructor, or if it is
0N/A * non-externalizable and its first non-serializable superclass defines an
0N/A * accessible no-arg constructor. Otherwise, returns false.
0N/A */
0N/A boolean isInstantiable() {
0N/A return (cons != null);
0N/A }
0N/A
0N/A /**
0N/A * Returns true if represented class is serializable (but not
0N/A * externalizable) and defines a conformant writeObject method. Otherwise,
0N/A * returns false.
0N/A */
0N/A boolean hasWriteObjectMethod() {
0N/A return (writeObjectMethod != null);
0N/A }
0N/A
0N/A /**
0N/A * Returns true if represented class is serializable (but not
0N/A * externalizable) and defines a conformant readObject method. Otherwise,
0N/A * returns false.
0N/A */
0N/A boolean hasReadObjectMethod() {
0N/A return (readObjectMethod != null);
0N/A }
0N/A
0N/A /**
0N/A * Returns true if represented class is serializable (but not
0N/A * externalizable) and defines a conformant readObjectNoData method.
0N/A * Otherwise, returns false.
0N/A */
0N/A boolean hasReadObjectNoDataMethod() {
0N/A return (readObjectNoDataMethod != null);
0N/A }
0N/A
0N/A /**
0N/A * Returns true if represented class is serializable or externalizable and
0N/A * defines a conformant writeReplace method. Otherwise, returns false.
0N/A */
0N/A boolean hasWriteReplaceMethod() {
0N/A return (writeReplaceMethod != null);
0N/A }
0N/A
0N/A /**
0N/A * Returns true if represented class is serializable or externalizable and
0N/A * defines a conformant readResolve method. Otherwise, returns false.
0N/A */
0N/A boolean hasReadResolveMethod() {
0N/A return (readResolveMethod != null);
0N/A }
0N/A
0N/A /**
0N/A * Creates a new instance of the represented class. If the class is
0N/A * externalizable, invokes its public no-arg constructor; otherwise, if the
0N/A * class is serializable, invokes the no-arg constructor of the first
0N/A * non-serializable superclass. Throws UnsupportedOperationException if
0N/A * this class descriptor is not associated with a class, if the associated
0N/A * class is non-serializable or if the appropriate no-arg constructor is
0N/A * inaccessible/unavailable.
0N/A */
0N/A Object newInstance()
0N/A throws InstantiationException, InvocationTargetException,
0N/A UnsupportedOperationException
0N/A {
0N/A if (cons != null) {
0N/A try {
0N/A return cons.newInstance();
0N/A } catch (IllegalAccessException ex) {
0N/A // should not occur, as access checks have been suppressed
0N/A throw new InternalError();
0N/A }
0N/A } else {
0N/A throw new UnsupportedOperationException();
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Invokes the writeObject method of the represented serializable class.
0N/A * Throws UnsupportedOperationException if this class descriptor is not
0N/A * associated with a class, or if the class is externalizable,
0N/A * non-serializable or does not define writeObject.
0N/A */
0N/A void invokeWriteObject(Object obj, ObjectOutputStream out)
0N/A throws IOException, UnsupportedOperationException
0N/A {
0N/A if (writeObjectMethod != null) {
0N/A try {
0N/A writeObjectMethod.invoke(obj, new Object[]{ out });
0N/A } catch (InvocationTargetException ex) {
0N/A Throwable th = ex.getTargetException();
0N/A if (th instanceof IOException) {
0N/A throw (IOException) th;
0N/A } else {
0N/A throwMiscException(th);
0N/A }
0N/A } catch (IllegalAccessException ex) {
0N/A // should not occur, as access checks have been suppressed
0N/A throw new InternalError();
0N/A }
0N/A } else {
0N/A throw new UnsupportedOperationException();
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Invokes the readObject method of the represented serializable class.
0N/A * Throws UnsupportedOperationException if this class descriptor is not
0N/A * associated with a class, or if the class is externalizable,
0N/A * non-serializable or does not define readObject.
0N/A */
0N/A void invokeReadObject(Object obj, ObjectInputStream in)
0N/A throws ClassNotFoundException, IOException,
0N/A UnsupportedOperationException
0N/A {
0N/A if (readObjectMethod != null) {
0N/A try {
0N/A readObjectMethod.invoke(obj, new Object[]{ in });
0N/A } catch (InvocationTargetException ex) {
0N/A Throwable th = ex.getTargetException();
0N/A if (th instanceof ClassNotFoundException) {
0N/A throw (ClassNotFoundException) th;
0N/A } else if (th instanceof IOException) {
0N/A throw (IOException) th;
0N/A } else {
0N/A throwMiscException(th);
0N/A }
0N/A } catch (IllegalAccessException ex) {
0N/A // should not occur, as access checks have been suppressed
0N/A throw new InternalError();
0N/A }
0N/A } else {
0N/A throw new UnsupportedOperationException();
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Invokes the readObjectNoData method of the represented serializable
0N/A * class. Throws UnsupportedOperationException if this class descriptor is
0N/A * not associated with a class, or if the class is externalizable,
0N/A * non-serializable or does not define readObjectNoData.
0N/A */
0N/A void invokeReadObjectNoData(Object obj)
0N/A throws IOException, UnsupportedOperationException
0N/A {
0N/A if (readObjectNoDataMethod != null) {
0N/A try {
0N/A readObjectNoDataMethod.invoke(obj, (Object[]) null);
0N/A } catch (InvocationTargetException ex) {
0N/A Throwable th = ex.getTargetException();
0N/A if (th instanceof ObjectStreamException) {
0N/A throw (ObjectStreamException) th;
0N/A } else {
0N/A throwMiscException(th);
0N/A }
0N/A } catch (IllegalAccessException ex) {
0N/A // should not occur, as access checks have been suppressed
0N/A throw new InternalError();
0N/A }
0N/A } else {
0N/A throw new UnsupportedOperationException();
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Invokes the writeReplace method of the represented serializable class and
0N/A * returns the result. Throws UnsupportedOperationException if this class
0N/A * descriptor is not associated with a class, or if the class is
0N/A * non-serializable or does not define writeReplace.
0N/A */
0N/A Object invokeWriteReplace(Object obj)
0N/A throws IOException, UnsupportedOperationException
0N/A {
0N/A if (writeReplaceMethod != null) {
0N/A try {
0N/A return writeReplaceMethod.invoke(obj, (Object[]) null);
0N/A } catch (InvocationTargetException ex) {
0N/A Throwable th = ex.getTargetException();
0N/A if (th instanceof ObjectStreamException) {
0N/A throw (ObjectStreamException) th;
0N/A } else {
0N/A throwMiscException(th);
0N/A throw new InternalError(); // never reached
0N/A }
0N/A } catch (IllegalAccessException ex) {
0N/A // should not occur, as access checks have been suppressed
0N/A throw new InternalError();
0N/A }
0N/A } else {
0N/A throw new UnsupportedOperationException();
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Invokes the readResolve method of the represented serializable class and
0N/A * returns the result. Throws UnsupportedOperationException if this class
0N/A * descriptor is not associated with a class, or if the class is
0N/A * non-serializable or does not define readResolve.
0N/A */
0N/A Object invokeReadResolve(Object obj)
0N/A throws IOException, UnsupportedOperationException
0N/A {
0N/A if (readResolveMethod != null) {
0N/A try {
0N/A return readResolveMethod.invoke(obj, (Object[]) null);
0N/A } catch (InvocationTargetException ex) {
0N/A Throwable th = ex.getTargetException();
0N/A if (th instanceof ObjectStreamException) {
0N/A throw (ObjectStreamException) th;
0N/A } else {
0N/A throwMiscException(th);
0N/A throw new InternalError(); // never reached
0N/A }
0N/A } catch (IllegalAccessException ex) {
0N/A // should not occur, as access checks have been suppressed
0N/A throw new InternalError();
0N/A }
0N/A } else {
0N/A throw new UnsupportedOperationException();
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Class representing the portion of an object's serialized form allotted
0N/A * to data described by a given class descriptor. If "hasData" is false,
0N/A * the object's serialized form does not contain data associated with the
0N/A * class descriptor.
0N/A */
0N/A static class ClassDataSlot {
0N/A
0N/A /** class descriptor "occupying" this slot */
0N/A final ObjectStreamClass desc;
0N/A /** true if serialized form includes data for this slot's descriptor */
0N/A final boolean hasData;
0N/A
0N/A ClassDataSlot(ObjectStreamClass desc, boolean hasData) {
0N/A this.desc = desc;
0N/A this.hasData = hasData;
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Returns array of ClassDataSlot instances representing the data layout
0N/A * (including superclass data) for serialized objects described by this
0N/A * class descriptor. ClassDataSlots are ordered by inheritance with those
0N/A * containing "higher" superclasses appearing first. The final
0N/A * ClassDataSlot contains a reference to this descriptor.
0N/A */
0N/A ClassDataSlot[] getClassDataLayout() throws InvalidClassException {
0N/A // REMIND: synchronize instead of relying on volatile?
0N/A if (dataLayout == null) {
0N/A dataLayout = getClassDataLayout0();
0N/A }
0N/A return dataLayout;
0N/A }
0N/A
0N/A private ClassDataSlot[] getClassDataLayout0()
0N/A throws InvalidClassException
0N/A {
0N/A ArrayList<ClassDataSlot> slots = new ArrayList<>();
0N/A Class<?> start = cl, end = cl;
0N/A
0N/A // locate closest non-serializable superclass
0N/A while (end != null && Serializable.class.isAssignableFrom(end)) {
0N/A end = end.getSuperclass();
0N/A }
0N/A
0N/A HashSet<String> oscNames = new HashSet<>(3);
0N/A
0N/A for (ObjectStreamClass d = this; d != null; d = d.superDesc) {
0N/A if (oscNames.contains(d.name)) {
0N/A throw new InvalidClassException("Circular reference.");
0N/A } else {
0N/A oscNames.add(d.name);
0N/A }
0N/A
0N/A // search up inheritance hierarchy for class with matching name
0N/A String searchName = (d.cl != null) ? d.cl.getName() : d.name;
0N/A Class<?> match = null;
0N/A for (Class<?> c = start; c != end; c = c.getSuperclass()) {
0N/A if (searchName.equals(c.getName())) {
0N/A match = c;
0N/A break;
0N/A }
0N/A }
0N/A
0N/A // add "no data" slot for each unmatched class below match
0N/A if (match != null) {
0N/A for (Class<?> c = start; c != match; c = c.getSuperclass()) {
0N/A slots.add(new ClassDataSlot(
0N/A ObjectStreamClass.lookup(c, true), false));
0N/A }
0N/A start = match.getSuperclass();
0N/A }
0N/A
0N/A // record descriptor/class pairing
0N/A slots.add(new ClassDataSlot(d.getVariantFor(match), true));
0N/A }
0N/A
0N/A // add "no data" slot for any leftover unmatched classes
0N/A for (Class<?> c = start; c != end; c = c.getSuperclass()) {
0N/A slots.add(new ClassDataSlot(
0N/A ObjectStreamClass.lookup(c, true), false));
0N/A }
0N/A
0N/A // order slots from superclass -> subclass
0N/A Collections.reverse(slots);
0N/A return slots.toArray(new ClassDataSlot[slots.size()]);
0N/A }
0N/A
0N/A /**
0N/A * Returns aggregate size (in bytes) of marshalled primitive field values
0N/A * for represented class.
0N/A */
0N/A int getPrimDataSize() {
0N/A return primDataSize;
0N/A }
/**
* Returns number of non-primitive serializable fields of represented
* class.
*/
int getNumObjFields() {
return numObjFields;
}
/**
* Fetches the serializable primitive field values of object obj and
* marshals them into byte array buf starting at offset 0. It is the
* responsibility of the caller to ensure that obj is of the proper type if
* non-null.
*/
void getPrimFieldValues(Object obj, byte[] buf) {
fieldRefl.getPrimFieldValues(obj, buf);
}
/**
* Sets the serializable primitive fields of object obj using values
* unmarshalled from byte array buf starting at offset 0. It is the
* responsibility of the caller to ensure that obj is of the proper type if
* non-null.
*/
void setPrimFieldValues(Object obj, byte[] buf) {
fieldRefl.setPrimFieldValues(obj, buf);
}
/**
* Fetches the serializable object field values of object obj and stores
* them in array vals starting at offset 0. It is the responsibility of
* the caller to ensure that obj is of the proper type if non-null.
*/
void getObjFieldValues(Object obj, Object[] vals) {
fieldRefl.getObjFieldValues(obj, vals);
}
/**
* Sets the serializable object fields of object obj using values from
* array vals starting at offset 0. It is the responsibility of the caller
* to ensure that obj is of the proper type if non-null.
*/
void setObjFieldValues(Object obj, Object[] vals) {
fieldRefl.setObjFieldValues(obj, vals);
}
/**
* Calculates and sets serializable field offsets, as well as primitive
* data size and object field count totals. Throws InvalidClassException
* if fields are illegally ordered.
*/
private void computeFieldOffsets() throws InvalidClassException {
primDataSize = 0;
numObjFields = 0;
int firstObjIndex = -1;
for (int i = 0; i < fields.length; i++) {
ObjectStreamField f = fields[i];
switch (f.getTypeCode()) {
case 'Z':
case 'B':
f.setOffset(primDataSize++);
break;
case 'C':
case 'S':
f.setOffset(primDataSize);
primDataSize += 2;
break;
case 'I':
case 'F':
f.setOffset(primDataSize);
primDataSize += 4;
break;
case 'J':
case 'D':
f.setOffset(primDataSize);
primDataSize += 8;
break;
case '[':
case 'L':
f.setOffset(numObjFields++);
if (firstObjIndex == -1) {
firstObjIndex = i;
}
break;
default:
throw new InternalError();
}
}
if (firstObjIndex != -1 &&
firstObjIndex + numObjFields != fields.length)
{
throw new InvalidClassException(name, "illegal field order");
}
}
/**
* If given class is the same as the class associated with this class
* descriptor, returns reference to this class descriptor. Otherwise,
* returns variant of this class descriptor bound to given class.
*/
private ObjectStreamClass getVariantFor(Class<?> cl)
throws InvalidClassException
{
if (this.cl == cl) {
return this;
}
ObjectStreamClass desc = new ObjectStreamClass();
if (isProxy) {
desc.initProxy(cl, null, superDesc);
} else {
desc.initNonProxy(this, cl, null, superDesc);
}
return desc;
}
/**
* Returns public no-arg constructor of given class, or null if none found.
* Access checks are disabled on the returned constructor (if any), since
* the defining class may still be non-public.
*/
private static Constructor getExternalizableConstructor(Class<?> cl) {
try {
Constructor cons = cl.getDeclaredConstructor((Class<?>[]) null);
cons.setAccessible(true);
return ((cons.getModifiers() & Modifier.PUBLIC) != 0) ?
cons : null;
} catch (NoSuchMethodException ex) {
return null;
}
}
/**
* Returns subclass-accessible no-arg constructor of first non-serializable
* superclass, or null if none found. Access checks are disabled on the
* returned constructor (if any).
*/
private static Constructor getSerializableConstructor(Class<?> cl) {
Class<?> initCl = cl;
while (Serializable.class.isAssignableFrom(initCl)) {
if ((initCl = initCl.getSuperclass()) == null) {
return null;
}
}
try {
Constructor cons = initCl.getDeclaredConstructor((Class<?>[]) null);
int mods = cons.getModifiers();
if ((mods & Modifier.PRIVATE) != 0 ||
((mods & (Modifier.PUBLIC | Modifier.PROTECTED)) == 0 &&
!packageEquals(cl, initCl)))
{
return null;
}
cons = reflFactory.newConstructorForSerialization(cl, cons);
cons.setAccessible(true);
return cons;
} catch (NoSuchMethodException ex) {
return null;
}
}
/**
* 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).
*/
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 non-static private method with given signature defined by given
* class, or null if none found. Access checks are disabled on the
* returned method (if any).
*/
private static Method getPrivateMethod(Class<?> cl, String name,
Class<?>[] argTypes,
Class<?> returnType)
{
try {
Method meth = cl.getDeclaredMethod(name, argTypes);
meth.setAccessible(true);
int mods = meth.getModifiers();
return ((meth.getReturnType() == returnType) &&
((mods & Modifier.STATIC) == 0) &&
((mods & Modifier.PRIVATE) != 0)) ? meth : null;
} catch (NoSuchMethodException ex) {
return null;
}
}
/**
* Returns true if classes are defined in the same runtime package, false
* otherwise.
*/
private static boolean packageEquals(Class<?> cl1, Class<?> cl2) {
return (cl1.getClassLoader() == cl2.getClassLoader() &&
getPackageName(cl1).equals(getPackageName(cl2)));
}
/**
* Returns package name of given class.
*/
private static String getPackageName(Class<?> cl) {
String s = cl.getName();
int i = s.lastIndexOf('[');
if (i >= 0) {
s = s.substring(i + 2);
}
i = s.lastIndexOf('.');
return (i >= 0) ? s.substring(0, i) : "";
}
/**
* Compares class names for equality, ignoring package names. Returns true
* if class names equal, false otherwise.
*/
private static boolean classNamesEqual(String name1, String name2) {
name1 = name1.substring(name1.lastIndexOf('.') + 1);
name2 = name2.substring(name2.lastIndexOf('.') + 1);
return name1.equals(name2);
}
/**
* Returns JVM type signature for given class.
*/
private static String getClassSignature(Class<?> cl) {
StringBuilder sbuf = new StringBuilder();
while (cl.isArray()) {
sbuf.append('[');
cl = cl.getComponentType();
}
if (cl.isPrimitive()) {
if (cl == Integer.TYPE) {
sbuf.append('I');
} else if (cl == Byte.TYPE) {
sbuf.append('B');
} else if (cl == Long.TYPE) {
sbuf.append('J');
} else if (cl == Float.TYPE) {
sbuf.append('F');
} else if (cl == Double.TYPE) {
sbuf.append('D');
} else if (cl == Short.TYPE) {
sbuf.append('S');
} else if (cl == Character.TYPE) {
sbuf.append('C');
} else if (cl == Boolean.TYPE) {
sbuf.append('Z');
} else if (cl == Void.TYPE) {
sbuf.append('V');
} else {
throw new InternalError();
}
} else {
sbuf.append('L' + cl.getName().replace('.', '/') + ';');
}
return sbuf.toString();
}
/**
* Returns JVM type signature for given list of parameters and return type.
*/
private static String getMethodSignature(Class<?>[] paramTypes,
Class<?> retType)
{
StringBuilder sbuf = new StringBuilder();
sbuf.append('(');
for (int i = 0; i < paramTypes.length; i++) {
sbuf.append(getClassSignature(paramTypes[i]));
}
sbuf.append(')');
sbuf.append(getClassSignature(retType));
return sbuf.toString();
}
/**
* Convenience method for throwing an exception that is either a
* RuntimeException, Error, or of some unexpected type (in which case it is
* wrapped inside an IOException).
*/
private static void throwMiscException(Throwable th) throws IOException {
if (th instanceof RuntimeException) {
throw (RuntimeException) th;
} else if (th instanceof Error) {
throw (Error) th;
} else {
IOException ex = new IOException("unexpected exception type");
ex.initCause(th);
throw ex;
}
}
/**
* Returns ObjectStreamField array describing the serializable fields of
* the given class. Serializable fields backed by an actual field of the
* class are represented by ObjectStreamFields with corresponding non-null
* Field objects. Throws InvalidClassException if the (explicitly
* declared) serializable fields are invalid.
*/
private static ObjectStreamField[] getSerialFields(Class<?> cl)
throws InvalidClassException
{
ObjectStreamField[] fields;
if (Serializable.class.isAssignableFrom(cl) &&
!Externalizable.class.isAssignableFrom(cl) &&
!Proxy.isProxyClass(cl) &&
!cl.isInterface())
{
if ((fields = getDeclaredSerialFields(cl)) == null) {
fields = getDefaultSerialFields(cl);
}
Arrays.sort(fields);
} else {
fields = NO_FIELDS;
}
return fields;
}
/**
* Returns serializable fields of given class as defined explicitly by a
* "serialPersistentFields" field, or null if no appropriate
* "serialPersistentFields" field is defined. Serializable fields backed
* by an actual field of the class are represented by ObjectStreamFields
* with corresponding non-null Field objects. For compatibility with past
* releases, a "serialPersistentFields" field with a null value is
* considered equivalent to not declaring "serialPersistentFields". Throws
* InvalidClassException if the declared serializable fields are
* invalid--e.g., if multiple fields share the same name.
*/
private static ObjectStreamField[] getDeclaredSerialFields(Class<?> cl)
throws InvalidClassException
{
ObjectStreamField[] serialPersistentFields = null;
try {
Field f = cl.getDeclaredField("serialPersistentFields");
int mask = Modifier.PRIVATE | Modifier.STATIC | Modifier.FINAL;
if ((f.getModifiers() & mask) == mask) {
f.setAccessible(true);
serialPersistentFields = (ObjectStreamField[]) f.get(null);
}
} catch (Exception ex) {
}
if (serialPersistentFields == null) {
return null;
} else if (serialPersistentFields.length == 0) {
return NO_FIELDS;
}
ObjectStreamField[] boundFields =
new ObjectStreamField[serialPersistentFields.length];
Set<String> fieldNames = new HashSet<>(serialPersistentFields.length);
for (int i = 0; i < serialPersistentFields.length; i++) {
ObjectStreamField spf = serialPersistentFields[i];
String fname = spf.getName();
if (fieldNames.contains(fname)) {
throw new InvalidClassException(
"multiple serializable fields named " + fname);
}
fieldNames.add(fname);
try {
Field f = cl.getDeclaredField(fname);
if ((f.getType() == spf.getType()) &&
((f.getModifiers() & Modifier.STATIC) == 0))
{
boundFields[i] =
new ObjectStreamField(f, spf.isUnshared(), true);
}
} catch (NoSuchFieldException ex) {
}
if (boundFields[i] == null) {
boundFields[i] = new ObjectStreamField(
fname, spf.getType(), spf.isUnshared());
}
}
return boundFields;
}
/**
* Returns array of ObjectStreamFields corresponding to all non-static
* non-transient fields declared by given class. Each ObjectStreamField
* contains a Field object for the field it represents. If no default
* serializable fields exist, NO_FIELDS is returned.
*/
private static ObjectStreamField[] getDefaultSerialFields(Class<?> cl) {
Field[] clFields = cl.getDeclaredFields();
ArrayList<ObjectStreamField> list = new ArrayList<>();
int mask = Modifier.STATIC | Modifier.TRANSIENT;
for (int i = 0; i < clFields.length; i++) {
if ((clFields[i].getModifiers() & mask) == 0) {
list.add(new ObjectStreamField(clFields[i], false, true));
}
}
int size = list.size();
return (size == 0) ? NO_FIELDS :
list.toArray(new ObjectStreamField[size]);
}
/**
* Returns explicit serial version UID value declared by given class, or
* null if none.
*/
private static Long getDeclaredSUID(Class<?> cl) {
try {
Field f = cl.getDeclaredField("serialVersionUID");
int mask = Modifier.STATIC | Modifier.FINAL;
if ((f.getModifiers() & mask) == mask) {
f.setAccessible(true);
return Long.valueOf(f.getLong(null));
}
} catch (Exception ex) {
}
return null;
}
/**
* Computes the default serial version UID value for the given class.
*/
private static long computeDefaultSUID(Class<?> cl) {
if (!Serializable.class.isAssignableFrom(cl) || Proxy.isProxyClass(cl))
{
return 0L;
}
try {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
DataOutputStream dout = new DataOutputStream(bout);
dout.writeUTF(cl.getName());
int classMods = cl.getModifiers() &
(Modifier.PUBLIC | Modifier.FINAL |
Modifier.INTERFACE | Modifier.ABSTRACT);
/*
* compensate for javac bug in which ABSTRACT bit was set for an
* interface only if the interface declared methods
*/
Method[] methods = cl.getDeclaredMethods();
if ((classMods & Modifier.INTERFACE) != 0) {
classMods = (methods.length > 0) ?
(classMods | Modifier.ABSTRACT) :
(classMods & ~Modifier.ABSTRACT);
}
dout.writeInt(classMods);
if (!cl.isArray()) {
/*
* compensate for change in 1.2FCS in which
* Class.getInterfaces() was modified to return Cloneable and
* Serializable for array classes.
*/
Class<?>[] interfaces = cl.getInterfaces();
String[] ifaceNames = new String[interfaces.length];
for (int i = 0; i < interfaces.length; i++) {
ifaceNames[i] = interfaces[i].getName();
}
Arrays.sort(ifaceNames);
for (int i = 0; i < ifaceNames.length; i++) {
dout.writeUTF(ifaceNames[i]);
}
}
Field[] fields = cl.getDeclaredFields();
MemberSignature[] fieldSigs = new MemberSignature[fields.length];
for (int i = 0; i < fields.length; i++) {
fieldSigs[i] = new MemberSignature(fields[i]);
}
Arrays.sort(fieldSigs, new Comparator<MemberSignature>() {
public int compare(MemberSignature ms1, MemberSignature ms2) {
return ms1.name.compareTo(ms2.name);
}
});
for (int i = 0; i < fieldSigs.length; i++) {
MemberSignature sig = fieldSigs[i];
int mods = sig.member.getModifiers() &
(Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED |
Modifier.STATIC | Modifier.FINAL | Modifier.VOLATILE |
Modifier.TRANSIENT);
if (((mods & Modifier.PRIVATE) == 0) ||
((mods & (Modifier.STATIC | Modifier.TRANSIENT)) == 0))
{
dout.writeUTF(sig.name);
dout.writeInt(mods);
dout.writeUTF(sig.signature);
}
}
if (hasStaticInitializer(cl)) {
dout.writeUTF("<clinit>");
dout.writeInt(Modifier.STATIC);
dout.writeUTF("()V");
}
Constructor[] cons = cl.getDeclaredConstructors();
MemberSignature[] consSigs = new MemberSignature[cons.length];
for (int i = 0; i < cons.length; i++) {
consSigs[i] = new MemberSignature(cons[i]);
}
Arrays.sort(consSigs, new Comparator<MemberSignature>() {
public int compare(MemberSignature ms1, MemberSignature ms2) {
return ms1.signature.compareTo(ms2.signature);
}
});
for (int i = 0; i < consSigs.length; i++) {
MemberSignature sig = consSigs[i];
int mods = sig.member.getModifiers() &
(Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED |
Modifier.STATIC | Modifier.FINAL |
Modifier.SYNCHRONIZED | Modifier.NATIVE |
Modifier.ABSTRACT | Modifier.STRICT);
if ((mods & Modifier.PRIVATE) == 0) {
dout.writeUTF("<init>");
dout.writeInt(mods);
dout.writeUTF(sig.signature.replace('/', '.'));
}
}
MemberSignature[] methSigs = new MemberSignature[methods.length];
for (int i = 0; i < methods.length; i++) {
methSigs[i] = new MemberSignature(methods[i]);
}
Arrays.sort(methSigs, new Comparator<MemberSignature>() {
public int compare(MemberSignature ms1, MemberSignature ms2) {
int comp = ms1.name.compareTo(ms2.name);
if (comp == 0) {
comp = ms1.signature.compareTo(ms2.signature);
}
return comp;
}
});
for (int i = 0; i < methSigs.length; i++) {
MemberSignature sig = methSigs[i];
int mods = sig.member.getModifiers() &
(Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED |
Modifier.STATIC | Modifier.FINAL |
Modifier.SYNCHRONIZED | Modifier.NATIVE |
Modifier.ABSTRACT | Modifier.STRICT);
if ((mods & Modifier.PRIVATE) == 0) {
dout.writeUTF(sig.name);
dout.writeInt(mods);
dout.writeUTF(sig.signature.replace('/', '.'));
}
}
dout.flush();
MessageDigest md = MessageDigest.getInstance("SHA");
byte[] hashBytes = md.digest(bout.toByteArray());
long hash = 0;
for (int i = Math.min(hashBytes.length, 8) - 1; i >= 0; i--) {
hash = (hash << 8) | (hashBytes[i] & 0xFF);
}
return hash;
} catch (IOException ex) {
throw new InternalError();
} catch (NoSuchAlgorithmException ex) {
throw new SecurityException(ex.getMessage());
}
}
/**
* Returns true if the given class defines a static initializer method,
* false otherwise.
*/
private native static boolean hasStaticInitializer(Class<?> cl);
/**
* Class for computing and caching field/constructor/method signatures
* during serialVersionUID calculation.
*/
private static class MemberSignature {
public final Member member;
public final String name;
public final String signature;
public MemberSignature(Field field) {
member = field;
name = field.getName();
signature = getClassSignature(field.getType());
}
public MemberSignature(Constructor cons) {
member = cons;
name = cons.getName();
signature = getMethodSignature(
cons.getParameterTypes(), Void.TYPE);
}
public MemberSignature(Method meth) {
member = meth;
name = meth.getName();
signature = getMethodSignature(
meth.getParameterTypes(), meth.getReturnType());
}
}
/**
* Class for setting and retrieving serializable field values in batch.
*/
// REMIND: dynamically generate these?
private static class FieldReflector {
/** handle for performing unsafe operations */
private static final Unsafe unsafe = Unsafe.getUnsafe();
/** fields to operate on */
private final ObjectStreamField[] fields;
/** number of primitive fields */
private final int numPrimFields;
/** unsafe field keys for reading fields - may contain dupes */
private final long[] readKeys;
/** unsafe fields keys for writing fields - no dupes */
private final long[] writeKeys;
/** field data offsets */
private final int[] offsets;
/** field type codes */
private final char[] typeCodes;
/** field types */
private final Class<?>[] types;
/**
* Constructs FieldReflector capable of setting/getting values from the
* subset of fields whose ObjectStreamFields contain non-null
* reflective Field objects. ObjectStreamFields with null Fields are
* treated as filler, for which get operations return default values
* and set operations discard given values.
*/
FieldReflector(ObjectStreamField[] fields) {
this.fields = fields;
int nfields = fields.length;
readKeys = new long[nfields];
writeKeys = new long[nfields];
offsets = new int[nfields];
typeCodes = new char[nfields];
ArrayList<Class<?>> typeList = new ArrayList<>();
Set<Long> usedKeys = new HashSet<>();
for (int i = 0; i < nfields; i++) {
ObjectStreamField f = fields[i];
Field rf = f.getField();
long key = (rf != null) ?
unsafe.objectFieldOffset(rf) : Unsafe.INVALID_FIELD_OFFSET;
readKeys[i] = key;
writeKeys[i] = usedKeys.add(key) ?
key : Unsafe.INVALID_FIELD_OFFSET;
offsets[i] = f.getOffset();
typeCodes[i] = f.getTypeCode();
if (!f.isPrimitive()) {
typeList.add((rf != null) ? rf.getType() : null);
}
}
types = typeList.toArray(new Class<?>[typeList.size()]);
numPrimFields = nfields - types.length;
}
/**
* Returns list of ObjectStreamFields representing fields operated on
* by this reflector. The shared/unshared values and Field objects
* contained by ObjectStreamFields in the list reflect their bindings
* to locally defined serializable fields.
*/
ObjectStreamField[] getFields() {
return fields;
}
/**
* Fetches the serializable primitive field values of object obj and
* marshals them into byte array buf starting at offset 0. The caller
* is responsible for ensuring that obj is of the proper type.
*/
void getPrimFieldValues(Object obj, byte[] buf) {
if (obj == null) {
throw new NullPointerException();
}
/* assuming checkDefaultSerialize() has been called on the class
* descriptor this FieldReflector was obtained from, no field keys
* in array should be equal to Unsafe.INVALID_FIELD_OFFSET.
*/
for (int i = 0; i < numPrimFields; i++) {
long key = readKeys[i];
int off = offsets[i];
switch (typeCodes[i]) {
case 'Z':
Bits.putBoolean(buf, off, unsafe.getBoolean(obj, key));
break;
case 'B':
buf[off] = unsafe.getByte(obj, key);
break;
case 'C':
Bits.putChar(buf, off, unsafe.getChar(obj, key));
break;
case 'S':
Bits.putShort(buf, off, unsafe.getShort(obj, key));
break;
case 'I':
Bits.putInt(buf, off, unsafe.getInt(obj, key));
break;
case 'F':
Bits.putFloat(buf, off, unsafe.getFloat(obj, key));
break;
case 'J':
Bits.putLong(buf, off, unsafe.getLong(obj, key));
break;
case 'D':
Bits.putDouble(buf, off, unsafe.getDouble(obj, key));
break;
default:
throw new InternalError();
}
}
}
/**
* Sets the serializable primitive fields of object obj using values
* unmarshalled from byte array buf starting at offset 0. The caller
* is responsible for ensuring that obj is of the proper type.
*/
void setPrimFieldValues(Object obj, byte[] buf) {
if (obj == null) {
throw new NullPointerException();
}
for (int i = 0; i < numPrimFields; i++) {
long key = writeKeys[i];
if (key == Unsafe.INVALID_FIELD_OFFSET) {
continue; // discard value
}
int off = offsets[i];
switch (typeCodes[i]) {
case 'Z':
unsafe.putBoolean(obj, key, Bits.getBoolean(buf, off));
break;
case 'B':
unsafe.putByte(obj, key, buf[off]);
break;
case 'C':
unsafe.putChar(obj, key, Bits.getChar(buf, off));
break;
case 'S':
unsafe.putShort(obj, key, Bits.getShort(buf, off));
break;
case 'I':
unsafe.putInt(obj, key, Bits.getInt(buf, off));
break;
case 'F':
unsafe.putFloat(obj, key, Bits.getFloat(buf, off));
break;
case 'J':
unsafe.putLong(obj, key, Bits.getLong(buf, off));
break;
case 'D':
unsafe.putDouble(obj, key, Bits.getDouble(buf, off));
break;
default:
throw new InternalError();
}
}
}
/**
* Fetches the serializable object field values of object obj and
* stores them in array vals starting at offset 0. The caller is
* responsible for ensuring that obj is of the proper type.
*/
void getObjFieldValues(Object obj, Object[] vals) {
if (obj == null) {
throw new NullPointerException();
}
/* assuming checkDefaultSerialize() has been called on the class
* descriptor this FieldReflector was obtained from, no field keys
* in array should be equal to Unsafe.INVALID_FIELD_OFFSET.
*/
for (int i = numPrimFields; i < fields.length; i++) {
switch (typeCodes[i]) {
case 'L':
case '[':
vals[offsets[i]] = unsafe.getObject(obj, readKeys[i]);
break;
default:
throw new InternalError();
}
}
}
/**
* Sets the serializable object fields of object obj using values from
* array vals starting at offset 0. The caller is responsible for
* ensuring that obj is of the proper type; however, attempts to set a
* field with a value of the wrong type will trigger an appropriate
* ClassCastException.
*/
void setObjFieldValues(Object obj, Object[] vals) {
if (obj == null) {
throw new NullPointerException();
}
for (int i = numPrimFields; i < fields.length; i++) {
long key = writeKeys[i];
if (key == Unsafe.INVALID_FIELD_OFFSET) {
continue; // discard value
}
switch (typeCodes[i]) {
case 'L':
case '[':
Object val = vals[offsets[i]];
if (val != null &&
!types[i - numPrimFields].isInstance(val))
{
Field f = fields[i].getField();
throw new ClassCastException(
"cannot assign instance of " +
val.getClass().getName() + " to field " +
f.getDeclaringClass().getName() + "." +
f.getName() + " of type " +
f.getType().getName() + " in instance of " +
obj.getClass().getName());
}
unsafe.putObject(obj, key, val);
break;
default:
throw new InternalError();
}
}
}
}
/**
* Matches given set of serializable fields with serializable fields
* described by the given local class descriptor, and returns a
* FieldReflector instance capable of setting/getting values from the
* subset of fields that match (non-matching fields are treated as filler,
* for which get operations return default values and set operations
* discard given values). Throws InvalidClassException if unresolvable
* type conflicts exist between the two sets of fields.
*/
private static FieldReflector getReflector(ObjectStreamField[] fields,
ObjectStreamClass localDesc)
throws InvalidClassException
{
// class irrelevant if no fields
Class<?> cl = (localDesc != null && fields.length > 0) ?
localDesc.cl : null;
processQueue(Caches.reflectorsQueue, Caches.reflectors);
FieldReflectorKey key = new FieldReflectorKey(cl, fields,
Caches.reflectorsQueue);
Reference<?> ref = Caches.reflectors.get(key);
Object entry = null;
if (ref != null) {
entry = ref.get();
}
EntryFuture future = null;
if (entry == null) {
EntryFuture newEntry = new EntryFuture();
Reference<?> newRef = new SoftReference<>(newEntry);
do {
if (ref != null) {
Caches.reflectors.remove(key, ref);
}
ref = Caches.reflectors.putIfAbsent(key, newRef);
if (ref != null) {
entry = ref.get();
}
} while (ref != null && entry == null);
if (entry == null) {
future = newEntry;
}
}
if (entry instanceof FieldReflector) { // check common case first
return (FieldReflector) entry;
} else if (entry instanceof EntryFuture) {
entry = ((EntryFuture) entry).get();
} else if (entry == null) {
try {
entry = new FieldReflector(matchFields(fields, localDesc));
} catch (Throwable th) {
entry = th;
}
future.set(entry);
Caches.reflectors.put(key, new SoftReference<Object>(entry));
}
if (entry instanceof FieldReflector) {
return (FieldReflector) entry;
} else if (entry instanceof InvalidClassException) {
throw (InvalidClassException) entry;
} else if (entry instanceof RuntimeException) {
throw (RuntimeException) entry;
} else if (entry instanceof Error) {
throw (Error) entry;
} else {
throw new InternalError("unexpected entry: " + entry);
}
}
/**
* FieldReflector cache lookup key. Keys are considered equal if they
* refer to the same class and equivalent field formats.
*/
private static class FieldReflectorKey extends WeakReference<Class<?>> {
private final String sigs;
private final int hash;
private final boolean nullClass;
FieldReflectorKey(Class<?> cl, ObjectStreamField[] fields,
ReferenceQueue<Class<?>> queue)
{
super(cl, queue);
nullClass = (cl == null);
StringBuilder sbuf = new StringBuilder();
for (int i = 0; i < fields.length; i++) {
ObjectStreamField f = fields[i];
sbuf.append(f.getName()).append(f.getSignature());
}
sigs = sbuf.toString();
hash = System.identityHashCode(cl) + sigs.hashCode();
}
public int hashCode() {
return hash;
}
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof FieldReflectorKey) {
FieldReflectorKey other = (FieldReflectorKey) obj;
Class<?> referent;
return (nullClass ? other.nullClass
: ((referent = get()) != null) &&
(referent == other.get())) &&
sigs.equals(other.sigs);
} else {
return false;
}
}
}
/**
* Matches given set of serializable fields with serializable fields
* obtained from the given local class descriptor (which contain bindings
* to reflective Field objects). Returns list of ObjectStreamFields in
* which each ObjectStreamField whose signature matches that of a local
* field contains a Field object for that field; unmatched
* ObjectStreamFields contain null Field objects. Shared/unshared settings
* of the returned ObjectStreamFields also reflect those of matched local
* ObjectStreamFields. Throws InvalidClassException if unresolvable type
* conflicts exist between the two sets of fields.
*/
private static ObjectStreamField[] matchFields(ObjectStreamField[] fields,
ObjectStreamClass localDesc)
throws InvalidClassException
{
ObjectStreamField[] localFields = (localDesc != null) ?
localDesc.fields : NO_FIELDS;
/*
* Even if fields == localFields, we cannot simply return localFields
* here. In previous implementations of serialization,
* ObjectStreamField.getType() returned Object.class if the
* ObjectStreamField represented a non-primitive field and belonged to
* a non-local class descriptor. To preserve this (questionable)
* behavior, the ObjectStreamField instances returned by matchFields
* cannot report non-primitive types other than Object.class; hence
* localFields cannot be returned directly.
*/
ObjectStreamField[] matches = new ObjectStreamField[fields.length];
for (int i = 0; i < fields.length; i++) {
ObjectStreamField f = fields[i], m = null;
for (int j = 0; j < localFields.length; j++) {
ObjectStreamField lf = localFields[j];
if (f.getName().equals(lf.getName())) {
if ((f.isPrimitive() || lf.isPrimitive()) &&
f.getTypeCode() != lf.getTypeCode())
{
throw new InvalidClassException(localDesc.name,
"incompatible types for field " + f.getName());
}
if (lf.getField() != null) {
m = new ObjectStreamField(
lf.getField(), lf.isUnshared(), false);
} else {
m = new ObjectStreamField(
lf.getName(), lf.getSignature(), lf.isUnshared());
}
}
}
if (m == null) {
m = new ObjectStreamField(
f.getName(), f.getSignature(), false);
}
m.setOffset(f.getOffset());
matches[i] = m;
}
return matches;
}
/**
* Removes from the specified map any keys that have been enqueued
* on the specified reference queue.
*/
static void processQueue(ReferenceQueue<Class<?>> queue,
ConcurrentMap<? extends
WeakReference<Class<?>>, ?> map)
{
Reference<? extends Class<?>> ref;
while((ref = queue.poll()) != null) {
map.remove(ref);
}
}
/**
* Weak key for Class objects.
*
**/
static class WeakClassKey extends WeakReference<Class<?>> {
/**
* saved value of the referent's identity hash code, to maintain
* a consistent hash code after the referent has been cleared
*/
private final int hash;
/**
* Create a new WeakClassKey to the given object, registered
* with a queue.
*/
WeakClassKey(Class<?> cl, ReferenceQueue<Class<?>> refQueue) {
super(cl, refQueue);
hash = System.identityHashCode(cl);
}
/**
* Returns the identity hash code of the original referent.
*/
public int hashCode() {
return hash;
}
/**
* Returns true if the given object is this identical
* WeakClassKey instance, or, if this object's referent has not
* been cleared, if the given object is another WeakClassKey
* instance with the identical non-null referent as this one.
*/
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof WeakClassKey) {
Object referent = get();
return (referent != null) &&
(referent == ((WeakClassKey) obj).get());
} else {
return false;
}
}
}
}