1. /*
  2. * @(#)ObjectStreamClass.java 1.137 04/05/05
  3. *
  4. * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. package java.io;
  8. import java.lang.reflect.Constructor;
  9. import java.lang.reflect.Field;
  10. import java.lang.reflect.InvocationTargetException;
  11. import java.lang.reflect.Member;
  12. import java.lang.reflect.Method;
  13. import java.lang.reflect.Modifier;
  14. import java.lang.reflect.Proxy;
  15. import java.security.AccessController;
  16. import java.security.MessageDigest;
  17. import java.security.NoSuchAlgorithmException;
  18. import java.security.PrivilegedAction;
  19. import java.util.ArrayList;
  20. import java.util.Arrays;
  21. import java.util.Collections;
  22. import java.util.Comparator;
  23. import java.util.HashSet;
  24. import java.util.Set;
  25. import sun.misc.SoftCache;
  26. import sun.misc.Unsafe;
  27. import sun.reflect.ReflectionFactory;
  28. /**
  29. * Serialization's descriptor for classes. It contains the name and
  30. * serialVersionUID of the class. The ObjectStreamClass for a specific class
  31. * loaded in this Java VM can be found/created using the lookup method.
  32. *
  33. * <p>The algorithm to compute the SerialVersionUID is described in
  34. * <a href="../../../guide/serialization/spec/class.doc4.html">Object
  35. * Serialization Specification, Section 4.4, Stream Unique Identifiers</a>.
  36. *
  37. * @author Mike Warres
  38. * @author Roger Riggs
  39. * @version 1.98 02/02/00
  40. * @see ObjectStreamField
  41. * @see <a href="../../../guide/serialization/spec/class.doc.html">Object Serialization Specification, Section 4, Class Descriptors</a>
  42. * @since JDK1.1
  43. */
  44. public class ObjectStreamClass implements Serializable {
  45. /** serialPersistentFields value indicating no serializable fields */
  46. public static final ObjectStreamField[] NO_FIELDS =
  47. new ObjectStreamField[0];
  48. private static final long serialVersionUID = -6120832682080437368L;
  49. private static final ObjectStreamField[] serialPersistentFields =
  50. NO_FIELDS;
  51. /** reflection factory for obtaining serialization constructors */
  52. private static final ReflectionFactory reflFactory = (ReflectionFactory)
  53. AccessController.doPrivileged(
  54. new ReflectionFactory.GetReflectionFactoryAction());
  55. /** cache mapping local classes -> descriptors */
  56. private static final SoftCache localDescs = new SoftCache(10);
  57. /** cache mapping field group/local desc pairs -> field reflectors */
  58. private static final SoftCache reflectors = new SoftCache(10);
  59. /** class associated with this descriptor (if any) */
  60. private Class cl;
  61. /** name of class represented by this descriptor */
  62. private String name;
  63. /** serialVersionUID of represented class (null if not computed yet) */
  64. private volatile Long suid;
  65. /** true if represents dynamic proxy class */
  66. private boolean isProxy;
  67. /** true if represents enum type */
  68. private boolean isEnum;
  69. /** true if represented class implements Serializable */
  70. private boolean serializable;
  71. /** true if represented class implements Externalizable */
  72. private boolean externalizable;
  73. /** true if desc has data written by class-defined writeObject method */
  74. private boolean hasWriteObjectData;
  75. /**
  76. * true if desc has externalizable data written in block data format; this
  77. * must be true by default to accommodate ObjectInputStream subclasses which
  78. * override readClassDescriptor() to return class descriptors obtained from
  79. * ObjectStreamClass.lookup() (see 4461737)
  80. */
  81. private boolean hasBlockExternalData = true;
  82. /** exception (if any) thrown while attempting to resolve class */
  83. private ClassNotFoundException resolveEx;
  84. /** exception (if any) to throw if non-enum deserialization attempted */
  85. private InvalidClassException deserializeEx;
  86. /** exception (if any) to throw if non-enum serialization attempted */
  87. private InvalidClassException serializeEx;
  88. /** exception (if any) to throw if default serialization attempted */
  89. private InvalidClassException defaultSerializeEx;
  90. /** serializable fields */
  91. private ObjectStreamField[] fields;
  92. /** aggregate marshalled size of primitive fields */
  93. private int primDataSize;
  94. /** number of non-primitive fields */
  95. private int numObjFields;
  96. /** reflector for setting/getting serializable field values */
  97. private FieldReflector fieldRefl;
  98. /** data layout of serialized objects described by this class desc */
  99. private volatile ClassDataSlot[] dataLayout;
  100. /** serialization-appropriate constructor, or null if none */
  101. private Constructor cons;
  102. /** class-defined writeObject method, or null if none */
  103. private Method writeObjectMethod;
  104. /** class-defined readObject method, or null if none */
  105. private Method readObjectMethod;
  106. /** class-defined readObjectNoData method, or null if none */
  107. private Method readObjectNoDataMethod;
  108. /** class-defined writeReplace method, or null if none */
  109. private Method writeReplaceMethod;
  110. /** class-defined readResolve method, or null if none */
  111. private Method readResolveMethod;
  112. /** local class descriptor for represented class (may point to self) */
  113. private ObjectStreamClass localDesc;
  114. /** superclass descriptor appearing in stream */
  115. private ObjectStreamClass superDesc;
  116. /**
  117. * Initializes native code.
  118. */
  119. private static native void initNative();
  120. static {
  121. initNative();
  122. }
  123. /**
  124. * Find the descriptor for a class that can be serialized. Creates an
  125. * ObjectStreamClass instance if one does not exist yet for class. Null is
  126. * returned if the specified class does not implement java.io.Serializable
  127. * or java.io.Externalizable.
  128. *
  129. * @param cl class for which to get the descriptor
  130. * @return the class descriptor for the specified class
  131. */
  132. public static ObjectStreamClass lookup(Class<?> cl) {
  133. return lookup(cl, false);
  134. }
  135. /**
  136. * The name of the class described by this descriptor.
  137. *
  138. * @return a <code>String</code> representing the fully qualified name of
  139. * the class
  140. */
  141. public String getName() {
  142. return name;
  143. }
  144. /**
  145. * Return the serialVersionUID for this class. The serialVersionUID
  146. * defines a set of classes all with the same name that have evolved from a
  147. * common root class and agree to be serialized and deserialized using a
  148. * common format. NonSerializable classes have a serialVersionUID of 0L.
  149. *
  150. * @return the SUID of the class described by this descriptor
  151. */
  152. public long getSerialVersionUID() {
  153. // REMIND: synchronize instead of relying on volatile?
  154. if (suid == null) {
  155. suid = (Long) AccessController.doPrivileged(
  156. new PrivilegedAction() {
  157. public Object run() {
  158. return new Long(computeDefaultSUID(cl));
  159. }
  160. }
  161. );
  162. }
  163. return suid.longValue();
  164. }
  165. /**
  166. * Return the class in the local VM that this version is mapped to. Null
  167. * is returned if there is no corresponding local class.
  168. *
  169. * @return the <code>Class</code> instance that this descriptor represents
  170. */
  171. public Class<?> forClass() {
  172. return cl;
  173. }
  174. /**
  175. * Return an array of the fields of this serializable class.
  176. *
  177. * @return an array containing an element for each persistent field of
  178. * this class. Returns an array of length zero if there are no
  179. * fields.
  180. * @since 1.2
  181. */
  182. public ObjectStreamField[] getFields() {
  183. return getFields(true);
  184. }
  185. /**
  186. * Get the field of this class by name.
  187. *
  188. * @param name the name of the data field to look for
  189. * @return The ObjectStreamField object of the named field or null if
  190. * there is no such named field.
  191. */
  192. public ObjectStreamField getField(String name) {
  193. return getField(name, null);
  194. }
  195. /**
  196. * Return a string describing this ObjectStreamClass.
  197. */
  198. public String toString() {
  199. return name + ": static final long serialVersionUID = " +
  200. getSerialVersionUID() + "L;";
  201. }
  202. /**
  203. * Looks up and returns class descriptor for given class, or null if class
  204. * is non-serializable and "all" is set to false.
  205. *
  206. * @param cl class to look up
  207. * @param all if true, return descriptors for all classes; if false, only
  208. * return descriptors for serializable classes
  209. */
  210. static ObjectStreamClass lookup(Class cl, boolean all) {
  211. if (!(all || Serializable.class.isAssignableFrom(cl))) {
  212. return null;
  213. }
  214. /*
  215. * Note: using the class directly as the key for storing entries does
  216. * not pin the class indefinitely, since SoftCache removes strong refs
  217. * to keys when the corresponding values are gc'ed.
  218. */
  219. Object entry;
  220. EntryFuture future = null;
  221. synchronized (localDescs) {
  222. if ((entry = localDescs.get(cl)) == null) {
  223. localDescs.put(cl, future = new EntryFuture());
  224. }
  225. }
  226. if (entry instanceof ObjectStreamClass) { // check common case first
  227. return (ObjectStreamClass) entry;
  228. }
  229. if (entry instanceof EntryFuture) {
  230. future = (EntryFuture) entry;
  231. if (future.getOwner() == Thread.currentThread()) {
  232. /*
  233. * Handle nested call situation described by 4803747: waiting
  234. * for future value to be set by a lookup() call further up the
  235. * stack will result in deadlock, so calculate and set the
  236. * future value here instead.
  237. */
  238. entry = null;
  239. } else {
  240. entry = future.get();
  241. }
  242. }
  243. if (entry == null) {
  244. try {
  245. entry = new ObjectStreamClass(cl);
  246. } catch (Throwable th) {
  247. entry = th;
  248. }
  249. if (future.set(entry)) {
  250. synchronized (localDescs) {
  251. localDescs.put(cl, entry);
  252. }
  253. } else {
  254. // nested lookup call already set future
  255. entry = future.get();
  256. }
  257. }
  258. if (entry instanceof ObjectStreamClass) {
  259. return (ObjectStreamClass) entry;
  260. } else if (entry instanceof RuntimeException) {
  261. throw (RuntimeException) entry;
  262. } else if (entry instanceof Error) {
  263. throw (Error) entry;
  264. } else {
  265. throw new InternalError("unexpected entry: " + entry);
  266. }
  267. }
  268. /**
  269. * Placeholder used in class descriptor and field reflector lookup tables
  270. * for an entry in the process of being initialized. (Internal) callers
  271. * which receive an EntryFuture belonging to another thread as the result
  272. * of a lookup should call the get() method of the EntryFuture; this will
  273. * return the actual entry once it is ready for use and has been set(). To
  274. * conserve objects, EntryFutures synchronize on themselves.
  275. */
  276. private static class EntryFuture {
  277. private static final Object unset = new Object();
  278. private final Thread owner = Thread.currentThread();
  279. private Object entry = unset;
  280. /**
  281. * Attempts to set the value contained by this EntryFuture. If the
  282. * EntryFuture's value has not been set already, then the value is
  283. * saved, any callers blocked in the get() method are notified, and
  284. * true is returned. If the value has already been set, then no saving
  285. * or notification occurs, and false is returned.
  286. */
  287. synchronized boolean set(Object entry) {
  288. if (this.entry != unset) {
  289. return false;
  290. }
  291. this.entry = entry;
  292. notifyAll();
  293. return true;
  294. }
  295. /**
  296. * Returns the value contained by this EntryFuture, blocking if
  297. * necessary until a value is set.
  298. */
  299. synchronized Object get() {
  300. boolean interrupted = false;
  301. while (entry == unset) {
  302. try {
  303. wait();
  304. } catch (InterruptedException ex) {
  305. interrupted = true;
  306. }
  307. }
  308. if (interrupted) {
  309. AccessController.doPrivileged(
  310. new PrivilegedAction() {
  311. public Object run() {
  312. Thread.currentThread().interrupt();
  313. return null;
  314. }
  315. }
  316. );
  317. }
  318. return entry;
  319. }
  320. /**
  321. * Returns the thread that created this EntryFuture.
  322. */
  323. Thread getOwner() {
  324. return owner;
  325. }
  326. }
  327. /**
  328. * Creates local class descriptor representing given class.
  329. */
  330. private ObjectStreamClass(final Class cl) {
  331. this.cl = cl;
  332. name = cl.getName();
  333. isProxy = Proxy.isProxyClass(cl);
  334. isEnum = Enum.class.isAssignableFrom(cl);
  335. serializable = Serializable.class.isAssignableFrom(cl);
  336. externalizable = Externalizable.class.isAssignableFrom(cl);
  337. Class superCl = cl.getSuperclass();
  338. superDesc = (superCl != null) ? lookup(superCl, false) : null;
  339. localDesc = this;
  340. if (serializable) {
  341. AccessController.doPrivileged(new PrivilegedAction() {
  342. public Object run() {
  343. if (isEnum) {
  344. suid = new Long(0);
  345. fields = NO_FIELDS;
  346. return null;
  347. }
  348. suid = getDeclaredSUID(cl);
  349. try {
  350. fields = getSerialFields(cl);
  351. computeFieldOffsets();
  352. } catch (InvalidClassException e) {
  353. serializeEx = deserializeEx = e;
  354. fields = NO_FIELDS;
  355. }
  356. if (externalizable) {
  357. cons = getExternalizableConstructor(cl);
  358. } else {
  359. cons = getSerializableConstructor(cl);
  360. writeObjectMethod = getPrivateMethod(cl, "writeObject",
  361. new Class[] { ObjectOutputStream.class },
  362. Void.TYPE);
  363. readObjectMethod = getPrivateMethod(cl, "readObject",
  364. new Class[] { ObjectInputStream.class },
  365. Void.TYPE);
  366. readObjectNoDataMethod = getPrivateMethod(
  367. cl, "readObjectNoData",
  368. new Class[0], Void.TYPE);
  369. hasWriteObjectData = (writeObjectMethod != null);
  370. }
  371. writeReplaceMethod = getInheritableMethod(
  372. cl, "writeReplace", new Class[0], Object.class);
  373. readResolveMethod = getInheritableMethod(
  374. cl, "readResolve", new Class[0], Object.class);
  375. return null;
  376. }
  377. });
  378. } else {
  379. suid = new Long(0);
  380. fields = NO_FIELDS;
  381. }
  382. try {
  383. fieldRefl = getReflector(fields, this);
  384. } catch (InvalidClassException ex) {
  385. // field mismatches impossible when matching local fields vs. self
  386. throw new InternalError();
  387. }
  388. if (deserializeEx == null) {
  389. if (isEnum) {
  390. deserializeEx = new InvalidClassException(name, "enum type");
  391. } else if (cons == null) {
  392. deserializeEx = new InvalidClassException(
  393. name, "no valid constructor");
  394. }
  395. }
  396. for (int i = 0; i < fields.length; i++) {
  397. if (fields[i].getField() == null) {
  398. defaultSerializeEx = new InvalidClassException(
  399. name, "unmatched serializable field(s) declared");
  400. }
  401. }
  402. }
  403. /**
  404. * Creates blank class descriptor which should be initialized via a
  405. * subsequent call to initProxy(), initNonProxy() or readNonProxy().
  406. */
  407. ObjectStreamClass() {
  408. }
  409. /**
  410. * Initializes class descriptor representing a proxy class.
  411. */
  412. void initProxy(Class cl,
  413. ClassNotFoundException resolveEx,
  414. ObjectStreamClass superDesc)
  415. throws InvalidClassException
  416. {
  417. this.cl = cl;
  418. this.resolveEx = resolveEx;
  419. this.superDesc = superDesc;
  420. isProxy = true;
  421. serializable = true;
  422. suid = new Long(0);
  423. fields = NO_FIELDS;
  424. if (cl != null) {
  425. localDesc = lookup(cl, true);
  426. if (!localDesc.isProxy) {
  427. throw new InvalidClassException(
  428. "cannot bind proxy descriptor to a non-proxy class");
  429. }
  430. name = localDesc.name;
  431. externalizable = localDesc.externalizable;
  432. cons = localDesc.cons;
  433. writeReplaceMethod = localDesc.writeReplaceMethod;
  434. readResolveMethod = localDesc.readResolveMethod;
  435. deserializeEx = localDesc.deserializeEx;
  436. }
  437. fieldRefl = getReflector(fields, localDesc);
  438. }
  439. /**
  440. * Initializes class descriptor representing a non-proxy class.
  441. */
  442. void initNonProxy(ObjectStreamClass model,
  443. Class cl,
  444. ClassNotFoundException resolveEx,
  445. ObjectStreamClass superDesc)
  446. throws InvalidClassException
  447. {
  448. this.cl = cl;
  449. this.resolveEx = resolveEx;
  450. this.superDesc = superDesc;
  451. name = model.name;
  452. suid = new Long(model.getSerialVersionUID());
  453. isProxy = false;
  454. isEnum = model.isEnum;
  455. serializable = model.serializable;
  456. externalizable = model.externalizable;
  457. hasBlockExternalData = model.hasBlockExternalData;
  458. hasWriteObjectData = model.hasWriteObjectData;
  459. fields = model.fields;
  460. primDataSize = model.primDataSize;
  461. numObjFields = model.numObjFields;
  462. if (cl != null) {
  463. localDesc = lookup(cl, true);
  464. if (localDesc.isProxy) {
  465. throw new InvalidClassException(
  466. "cannot bind non-proxy descriptor to a proxy class");
  467. }
  468. if (isEnum != localDesc.isEnum) {
  469. throw new InvalidClassException(isEnum ?
  470. "cannot bind enum descriptor to a non-enum class" :
  471. "cannot bind non-enum descriptor to an enum class");
  472. }
  473. if (serializable == localDesc.serializable &&
  474. !cl.isArray() &&
  475. suid.longValue() != localDesc.getSerialVersionUID())
  476. {
  477. throw new InvalidClassException(localDesc.name,
  478. "local class incompatible: " +
  479. "stream classdesc serialVersionUID = " + suid +
  480. ", local class serialVersionUID = " +
  481. localDesc.getSerialVersionUID());
  482. }
  483. if (!classNamesEqual(name, localDesc.name)) {
  484. throw new InvalidClassException(localDesc.name,
  485. "local class name incompatible with stream class " +
  486. "name \"" + name + "\"");
  487. }
  488. if (!isEnum) {
  489. if ((serializable == localDesc.serializable) &&
  490. (externalizable != localDesc.externalizable))
  491. {
  492. throw new InvalidClassException(localDesc.name,
  493. "Serializable incompatible with Externalizable");
  494. }
  495. if ((serializable != localDesc.serializable) ||
  496. (externalizable != localDesc.externalizable) ||
  497. !(serializable || externalizable))
  498. {
  499. deserializeEx = new InvalidClassException(localDesc.name,
  500. "class invalid for deserialization");
  501. }
  502. }
  503. cons = localDesc.cons;
  504. writeObjectMethod = localDesc.writeObjectMethod;
  505. readObjectMethod = localDesc.readObjectMethod;
  506. readObjectNoDataMethod = localDesc.readObjectNoDataMethod;
  507. writeReplaceMethod = localDesc.writeReplaceMethod;
  508. readResolveMethod = localDesc.readResolveMethod;
  509. if (deserializeEx == null) {
  510. deserializeEx = localDesc.deserializeEx;
  511. }
  512. }
  513. fieldRefl = getReflector(fields, localDesc);
  514. // reassign to matched fields so as to reflect local unshared settings
  515. fields = fieldRefl.getFields();
  516. }
  517. /**
  518. * Reads non-proxy class descriptor information from given input stream.
  519. * The resulting class descriptor is not fully functional; it can only be
  520. * used as input to the ObjectInputStream.resolveClass() and
  521. * ObjectStreamClass.initNonProxy() methods.
  522. */
  523. void readNonProxy(ObjectInputStream in)
  524. throws IOException, ClassNotFoundException
  525. {
  526. name = in.readUTF();
  527. suid = new Long(in.readLong());
  528. isProxy = false;
  529. byte flags = in.readByte();
  530. hasWriteObjectData =
  531. ((flags & ObjectStreamConstants.SC_WRITE_METHOD) != 0);
  532. hasBlockExternalData =
  533. ((flags & ObjectStreamConstants.SC_BLOCK_DATA) != 0);
  534. externalizable =
  535. ((flags & ObjectStreamConstants.SC_EXTERNALIZABLE) != 0);
  536. boolean sflag =
  537. ((flags & ObjectStreamConstants.SC_SERIALIZABLE) != 0);
  538. if (externalizable && sflag) {
  539. throw new InvalidClassException(
  540. name, "serializable and externalizable flags conflict");
  541. }
  542. serializable = externalizable || sflag;
  543. isEnum = ((flags & ObjectStreamConstants.SC_ENUM) != 0);
  544. if (isEnum && suid.longValue() != 0L) {
  545. throw new InvalidClassException(name,
  546. "enum descriptor has non-zero serialVersionUID: " + suid);
  547. }
  548. int numFields = in.readShort();
  549. if (isEnum && numFields != 0) {
  550. throw new InvalidClassException(name,
  551. "enum descriptor has non-zero field count: " + numFields);
  552. }
  553. fields = (numFields > 0) ?
  554. new ObjectStreamField[numFields] : NO_FIELDS;
  555. for (int i = 0; i < numFields; i++) {
  556. char tcode = (char) in.readByte();
  557. String fname = in.readUTF();
  558. String signature = ((tcode == 'L') || (tcode == '[')) ?
  559. in.readTypeString() : new String(new char[] { tcode });
  560. try {
  561. fields[i] = new ObjectStreamField(fname, signature, false);
  562. } catch (RuntimeException e) {
  563. throw (IOException) new InvalidClassException(name,
  564. "invalid descriptor for field " + fname).initCause(e);
  565. }
  566. }
  567. computeFieldOffsets();
  568. }
  569. /**
  570. * Writes non-proxy class descriptor information to given output stream.
  571. */
  572. void writeNonProxy(ObjectOutputStream out) throws IOException {
  573. out.writeUTF(name);
  574. out.writeLong(getSerialVersionUID());
  575. byte flags = 0;
  576. if (externalizable) {
  577. flags |= ObjectStreamConstants.SC_EXTERNALIZABLE;
  578. int protocol = out.getProtocolVersion();
  579. if (protocol != ObjectStreamConstants.PROTOCOL_VERSION_1) {
  580. flags |= ObjectStreamConstants.SC_BLOCK_DATA;
  581. }
  582. } else if (serializable) {
  583. flags |= ObjectStreamConstants.SC_SERIALIZABLE;
  584. }
  585. if (hasWriteObjectData) {
  586. flags |= ObjectStreamConstants.SC_WRITE_METHOD;
  587. }
  588. if (isEnum) {
  589. flags |= ObjectStreamConstants.SC_ENUM;
  590. }
  591. out.writeByte(flags);
  592. out.writeShort(fields.length);
  593. for (int i = 0; i < fields.length; i++) {
  594. ObjectStreamField f = fields[i];
  595. out.writeByte(f.getTypeCode());
  596. out.writeUTF(f.getName());
  597. if (!f.isPrimitive()) {
  598. out.writeTypeString(f.getTypeString());
  599. }
  600. }
  601. }
  602. /**
  603. * Returns ClassNotFoundException (if any) thrown while attempting to
  604. * resolve local class corresponding to this class descriptor.
  605. */
  606. ClassNotFoundException getResolveException() {
  607. return resolveEx;
  608. }
  609. /**
  610. * Throws an InvalidClassException if object instances referencing this
  611. * class descriptor should not be allowed to deserialize. This method does
  612. * not apply to deserialization of enum constants.
  613. */
  614. void checkDeserialize() throws InvalidClassException {
  615. if (deserializeEx != null) {
  616. throw deserializeEx;
  617. }
  618. }
  619. /**
  620. * Throws an InvalidClassException if objects whose class is represented by
  621. * this descriptor should not be allowed to serialize. This method does
  622. * not apply to serialization of enum constants.
  623. */
  624. void checkSerialize() throws InvalidClassException {
  625. if (serializeEx != null) {
  626. throw serializeEx;
  627. }
  628. }
  629. /**
  630. * Throws an InvalidClassException if objects whose class is represented by
  631. * this descriptor should not be permitted to use default serialization
  632. * (e.g., if the class declares serializable fields that do not correspond
  633. * to actual fields, and hence must use the GetField API). This method
  634. * does not apply to deserialization of enum constants.
  635. */
  636. void checkDefaultSerialize() throws InvalidClassException {
  637. if (defaultSerializeEx != null) {
  638. throw defaultSerializeEx;
  639. }
  640. }
  641. /**
  642. * Returns superclass descriptor. Note that on the receiving side, the
  643. * superclass descriptor may be bound to a class that is not a superclass
  644. * of the subclass descriptor's bound class.
  645. */
  646. ObjectStreamClass getSuperDesc() {
  647. return superDesc;
  648. }
  649. /**
  650. * Returns the "local" class descriptor for the class associated with this
  651. * class descriptor (i.e., the result of
  652. * ObjectStreamClass.lookup(this.forClass())) or null if there is no class
  653. * associated with this descriptor.
  654. */
  655. ObjectStreamClass getLocalDesc() {
  656. return localDesc;
  657. }
  658. /**
  659. * Returns arrays of ObjectStreamFields representing the serializable
  660. * fields of the represented class. If copy is true, a clone of this class
  661. * descriptor's field array is returned, otherwise the array itself is
  662. * returned.
  663. */
  664. ObjectStreamField[] getFields(boolean copy) {
  665. return copy ? (ObjectStreamField[]) fields.clone() : fields;
  666. }
  667. /**
  668. * Looks up a serializable field of the represented class by name and type.
  669. * A specified type of null matches all types, Object.class matches all
  670. * non-primitive types, and any other non-null type matches assignable
  671. * types only. Returns matching field, or null if no match found.
  672. */
  673. ObjectStreamField getField(String name, Class type) {
  674. for (int i = 0; i < fields.length; i++) {
  675. ObjectStreamField f = fields[i];
  676. if (f.getName().equals(name)) {
  677. if (type == null ||
  678. (type == Object.class && !f.isPrimitive()))
  679. {
  680. return f;
  681. }
  682. Class ftype = f.getType();
  683. if (ftype != null && type.isAssignableFrom(ftype)) {
  684. return f;
  685. }
  686. }
  687. }
  688. return null;
  689. }
  690. /**
  691. * Returns true if class descriptor represents a dynamic proxy class, false
  692. * otherwise.
  693. */
  694. boolean isProxy() {
  695. return isProxy;
  696. }
  697. /**
  698. * Returns true if class descriptor represents an enum type, false
  699. * otherwise.
  700. */
  701. boolean isEnum() {
  702. return isEnum;
  703. }
  704. /**
  705. * Returns true if represented class implements Externalizable, false
  706. * otherwise.
  707. */
  708. boolean isExternalizable() {
  709. return externalizable;
  710. }
  711. /**
  712. * Returns true if represented class implements Serializable, false
  713. * otherwise.
  714. */
  715. boolean isSerializable() {
  716. return serializable;
  717. }
  718. /**
  719. * Returns true if class descriptor represents externalizable class that
  720. * has written its data in 1.2 (block data) format, false otherwise.
  721. */
  722. boolean hasBlockExternalData() {
  723. return hasBlockExternalData;
  724. }
  725. /**
  726. * Returns true if class descriptor represents serializable (but not
  727. * externalizable) class which has written its data via a custom
  728. * writeObject() method, false otherwise.
  729. */
  730. boolean hasWriteObjectData() {
  731. return hasWriteObjectData;
  732. }
  733. /**
  734. * Returns true if represented class is serializable/externalizable and can
  735. * be instantiated by the serialization runtime--i.e., if it is
  736. * externalizable and defines a public no-arg constructor, or if it is
  737. * non-externalizable and its first non-serializable superclass defines an
  738. * accessible no-arg constructor. Otherwise, returns false.
  739. */
  740. boolean isInstantiable() {
  741. return (cons != null);
  742. }
  743. /**
  744. * Returns true if represented class is serializable (but not
  745. * externalizable) and defines a conformant writeObject method. Otherwise,
  746. * returns false.
  747. */
  748. boolean hasWriteObjectMethod() {
  749. return (writeObjectMethod != null);
  750. }
  751. /**
  752. * Returns true if represented class is serializable (but not
  753. * externalizable) and defines a conformant readObject method. Otherwise,
  754. * returns false.
  755. */
  756. boolean hasReadObjectMethod() {
  757. return (readObjectMethod != null);
  758. }
  759. /**
  760. * Returns true if represented class is serializable (but not
  761. * externalizable) and defines a conformant readObjectNoData method.
  762. * Otherwise, returns false.
  763. */
  764. boolean hasReadObjectNoDataMethod() {
  765. return (readObjectNoDataMethod != null);
  766. }
  767. /**
  768. * Returns true if represented class is serializable or externalizable and
  769. * defines a conformant writeReplace method. Otherwise, returns false.
  770. */
  771. boolean hasWriteReplaceMethod() {
  772. return (writeReplaceMethod != null);
  773. }
  774. /**
  775. * Returns true if represented class is serializable or externalizable and
  776. * defines a conformant readResolve method. Otherwise, returns false.
  777. */
  778. boolean hasReadResolveMethod() {
  779. return (readResolveMethod != null);
  780. }
  781. /**
  782. * Creates a new instance of the represented class. If the class is
  783. * externalizable, invokes its public no-arg constructor; otherwise, if the
  784. * class is serializable, invokes the no-arg constructor of the first
  785. * non-serializable superclass. Throws UnsupportedOperationException if
  786. * this class descriptor is not associated with a class, if the associated
  787. * class is non-serializable or if the appropriate no-arg constructor is
  788. * inaccessible/unavailable.
  789. */
  790. Object newInstance()
  791. throws InstantiationException, InvocationTargetException,
  792. UnsupportedOperationException
  793. {
  794. if (cons != null) {
  795. try {
  796. return cons.newInstance(null);
  797. } catch (IllegalAccessException ex) {
  798. // should not occur, as access checks have been suppressed
  799. throw new InternalError();
  800. }
  801. } else {
  802. throw new UnsupportedOperationException();
  803. }
  804. }
  805. /**
  806. * Invokes the writeObject method of the represented serializable class.
  807. * Throws UnsupportedOperationException if this class descriptor is not
  808. * associated with a class, or if the class is externalizable,
  809. * non-serializable or does not define writeObject.
  810. */
  811. void invokeWriteObject(Object obj, ObjectOutputStream out)
  812. throws IOException, UnsupportedOperationException
  813. {
  814. if (writeObjectMethod != null) {
  815. try {
  816. writeObjectMethod.invoke(obj, new Object[]{ out });
  817. } catch (InvocationTargetException ex) {
  818. Throwable th = ex.getTargetException();
  819. if (th instanceof IOException) {
  820. throw (IOException) th;
  821. } else {
  822. throwMiscException(th);
  823. }
  824. } catch (IllegalAccessException ex) {
  825. // should not occur, as access checks have been suppressed
  826. throw new InternalError();
  827. }
  828. } else {
  829. throw new UnsupportedOperationException();
  830. }
  831. }
  832. /**
  833. * Invokes the readObject method of the represented serializable class.
  834. * Throws UnsupportedOperationException if this class descriptor is not
  835. * associated with a class, or if the class is externalizable,
  836. * non-serializable or does not define readObject.
  837. */
  838. void invokeReadObject(Object obj, ObjectInputStream in)
  839. throws ClassNotFoundException, IOException,
  840. UnsupportedOperationException
  841. {
  842. if (readObjectMethod != null) {
  843. try {
  844. readObjectMethod.invoke(obj, new Object[]{ in });
  845. } catch (InvocationTargetException ex) {
  846. Throwable th = ex.getTargetException();
  847. if (th instanceof ClassNotFoundException) {
  848. throw (ClassNotFoundException) th;
  849. } else if (th instanceof IOException) {
  850. throw (IOException) th;
  851. } else {
  852. throwMiscException(th);
  853. }
  854. } catch (IllegalAccessException ex) {
  855. // should not occur, as access checks have been suppressed
  856. throw new InternalError();
  857. }
  858. } else {
  859. throw new UnsupportedOperationException();
  860. }
  861. }
  862. /**
  863. * Invokes the readObjectNoData method of the represented serializable
  864. * class. Throws UnsupportedOperationException if this class descriptor is
  865. * not associated with a class, or if the class is externalizable,
  866. * non-serializable or does not define readObjectNoData.
  867. */
  868. void invokeReadObjectNoData(Object obj)
  869. throws IOException, UnsupportedOperationException
  870. {
  871. if (readObjectNoDataMethod != null) {
  872. try {
  873. readObjectNoDataMethod.invoke(obj, null);
  874. } catch (InvocationTargetException ex) {
  875. Throwable th = ex.getTargetException();
  876. if (th instanceof ObjectStreamException) {
  877. throw (ObjectStreamException) th;
  878. } else {
  879. throwMiscException(th);
  880. }
  881. } catch (IllegalAccessException ex) {
  882. // should not occur, as access checks have been suppressed
  883. throw new InternalError();
  884. }
  885. } else {
  886. throw new UnsupportedOperationException();
  887. }
  888. }
  889. /**
  890. * Invokes the writeReplace method of the represented serializable class and
  891. * returns the result. Throws UnsupportedOperationException if this class
  892. * descriptor is not associated with a class, or if the class is
  893. * non-serializable or does not define writeReplace.
  894. */
  895. Object invokeWriteReplace(Object obj)
  896. throws IOException, UnsupportedOperationException
  897. {
  898. if (writeReplaceMethod != null) {
  899. try {
  900. return writeReplaceMethod.invoke(obj, null);
  901. } catch (InvocationTargetException ex) {
  902. Throwable th = ex.getTargetException();
  903. if (th instanceof ObjectStreamException) {
  904. throw (ObjectStreamException) th;
  905. } else {
  906. throwMiscException(th);
  907. throw new InternalError(); // never reached
  908. }
  909. } catch (IllegalAccessException ex) {
  910. // should not occur, as access checks have been suppressed
  911. throw new InternalError();
  912. }
  913. } else {
  914. throw new UnsupportedOperationException();
  915. }
  916. }
  917. /**
  918. * Invokes the readResolve method of the represented serializable class and
  919. * returns the result. Throws UnsupportedOperationException if this class
  920. * descriptor is not associated with a class, or if the class is
  921. * non-serializable or does not define readResolve.
  922. */
  923. Object invokeReadResolve(Object obj)
  924. throws IOException, UnsupportedOperationException
  925. {
  926. if (readResolveMethod != null) {
  927. try {
  928. return readResolveMethod.invoke(obj, null);
  929. } catch (InvocationTargetException ex) {
  930. Throwable th = ex.getTargetException();
  931. if (th instanceof ObjectStreamException) {
  932. throw (ObjectStreamException) th;
  933. } else {
  934. throwMiscException(th);
  935. throw new InternalError(); // never reached
  936. }
  937. } catch (IllegalAccessException ex) {
  938. // should not occur, as access checks have been suppressed
  939. throw new InternalError();
  940. }
  941. } else {
  942. throw new UnsupportedOperationException();
  943. }
  944. }
  945. /**
  946. * Class representing the portion of an object's serialized form allotted
  947. * to data described by a given class descriptor. If "hasData" is false,
  948. * the object's serialized form does not contain data associated with the
  949. * class descriptor.
  950. */
  951. static class ClassDataSlot {
  952. /** class descriptor "occupying" this slot */
  953. final ObjectStreamClass desc;
  954. /** true if serialized form includes data for this slot's descriptor */
  955. final boolean hasData;
  956. ClassDataSlot(ObjectStreamClass desc, boolean hasData) {
  957. this.desc = desc;
  958. this.hasData = hasData;
  959. }
  960. }
  961. /**
  962. * Returns array of ClassDataSlot instances representing the data layout
  963. * (including superclass data) for serialized objects described by this
  964. * class descriptor. ClassDataSlots are ordered by inheritance with those
  965. * containing "higher" superclasses appearing first. The final
  966. * ClassDataSlot contains a reference to this descriptor.
  967. */
  968. ClassDataSlot[] getClassDataLayout() throws InvalidClassException {
  969. // REMIND: synchronize instead of relying on volatile?
  970. if (dataLayout == null) {
  971. dataLayout = getClassDataLayout0();
  972. }
  973. return dataLayout;
  974. }
  975. private ClassDataSlot[] getClassDataLayout0()
  976. throws InvalidClassException
  977. {
  978. ArrayList slots = new ArrayList();
  979. Class start = cl, end = cl;
  980. // locate closest non-serializable superclass
  981. while (end != null && Serializable.class.isAssignableFrom(end)) {
  982. end = end.getSuperclass();
  983. }
  984. for (ObjectStreamClass d = this; d != null; d = d.superDesc) {
  985. // search up inheritance hierarchy for class with matching name
  986. String searchName = (d.cl != null) ? d.cl.getName() : d.name;
  987. Class match = null;
  988. for (Class c = start; c != end; c = c.getSuperclass()) {
  989. if (searchName.equals(c.getName())) {
  990. match = c;
  991. break;
  992. }
  993. }
  994. // add "no data" slot for each unmatched class below match
  995. if (match != null) {
  996. for (Class c = start; c != match; c = c.getSuperclass()) {
  997. slots.add(new ClassDataSlot(
  998. ObjectStreamClass.lookup(c, true), false));
  999. }
  1000. start = match.getSuperclass();
  1001. }
  1002. // record descriptor/class pairing
  1003. slots.add(new ClassDataSlot(d.getVariantFor(match), true));
  1004. }
  1005. // add "no data" slot for any leftover unmatched classes
  1006. for (Class c = start; c != end; c = c.getSuperclass()) {
  1007. slots.add(new ClassDataSlot(
  1008. ObjectStreamClass.lookup(c, true), false));
  1009. }
  1010. // order slots from superclass -> subclass
  1011. Collections.reverse(slots);
  1012. return (ClassDataSlot[])
  1013. slots.toArray(new ClassDataSlot[slots.size()]);
  1014. }
  1015. /**
  1016. * Returns aggregate size (in bytes) of marshalled primitive field values
  1017. * for represented class.
  1018. */
  1019. int getPrimDataSize() {
  1020. return primDataSize;
  1021. }
  1022. /**
  1023. * Returns number of non-primitive serializable fields of represented
  1024. * class.
  1025. */
  1026. int getNumObjFields() {
  1027. return numObjFields;
  1028. }
  1029. /**
  1030. * Fetches the serializable primitive field values of object obj and
  1031. * marshals them into byte array buf starting at offset 0. It is the
  1032. * responsibility of the caller to ensure that obj is of the proper type if
  1033. * non-null.
  1034. */
  1035. void getPrimFieldValues(Object obj, byte[] buf) {
  1036. fieldRefl.getPrimFieldValues(obj, buf);
  1037. }
  1038. /**
  1039. * Sets the serializable primitive fields of object obj using values
  1040. * unmarshalled from byte array buf starting at offset 0. It is the
  1041. * responsibility of the caller to ensure that obj is of the proper type if
  1042. * non-null.
  1043. */
  1044. void setPrimFieldValues(Object obj, byte[] buf) {
  1045. fieldRefl.setPrimFieldValues(obj, buf);
  1046. }
  1047. /**
  1048. * Fetches the serializable object field values of object obj and stores
  1049. * them in array vals starting at offset 0. It is the responsibility of
  1050. * the caller to ensure that obj is of the proper type if non-null.
  1051. */
  1052. void getObjFieldValues(Object obj, Object[] vals) {
  1053. fieldRefl.getObjFieldValues(obj, vals);
  1054. }
  1055. /**
  1056. * Sets the serializable object fields of object obj using values from
  1057. * array vals starting at offset 0. It is the responsibility of the caller
  1058. * to ensure that obj is of the proper type if non-null.
  1059. */
  1060. void setObjFieldValues(Object obj, Object[] vals) {
  1061. fieldRefl.setObjFieldValues(obj, vals);
  1062. }
  1063. /**
  1064. * Calculates and sets serializable field offsets, as well as primitive
  1065. * data size and object field count totals. Throws InvalidClassException
  1066. * if fields are illegally ordered.
  1067. */
  1068. private void computeFieldOffsets() throws InvalidClassException {
  1069. primDataSize = 0;
  1070. numObjFields = 0;
  1071. int firstObjIndex = -1;
  1072. for (int i = 0; i < fields.length; i++) {
  1073. ObjectStreamField f = fields[i];
  1074. switch (f.getTypeCode()) {
  1075. case 'Z':
  1076. case 'B':
  1077. f.setOffset(primDataSize++);
  1078. break;
  1079. case 'C':
  1080. case 'S':
  1081. f.setOffset(primDataSize);
  1082. primDataSize += 2;
  1083. break;
  1084. case 'I':
  1085. case 'F':
  1086. f.setOffset(primDataSize);
  1087. primDataSize += 4;
  1088. break;
  1089. case 'J':
  1090. case 'D':
  1091. f.setOffset(primDataSize);
  1092. primDataSize += 8;
  1093. break;
  1094. case '[':
  1095. case 'L':
  1096. f.setOffset(numObjFields++);
  1097. if (firstObjIndex == -1) {
  1098. firstObjIndex = i;
  1099. }
  1100. break;
  1101. default:
  1102. throw new InternalError();
  1103. }
  1104. }
  1105. if (firstObjIndex != -1 &&
  1106. firstObjIndex + numObjFields != fields.length)
  1107. {
  1108. throw new InvalidClassException(name, "illegal field order");
  1109. }
  1110. }
  1111. /**
  1112. * If given class is the same as the class associated with this class
  1113. * descriptor, returns reference to this class descriptor. Otherwise,
  1114. * returns variant of this class descriptor bound to given class.
  1115. */
  1116. private ObjectStreamClass getVariantFor(Class cl)
  1117. throws InvalidClassException
  1118. {
  1119. if (this.cl == cl) {
  1120. return this;
  1121. }
  1122. ObjectStreamClass desc = new ObjectStreamClass();
  1123. if (isProxy) {
  1124. desc.initProxy(cl, null, superDesc);
  1125. } else {
  1126. desc.initNonProxy(this, cl, null, superDesc);
  1127. }
  1128. return desc;
  1129. }
  1130. /**
  1131. * Returns public no-arg constructor of given class, or null if none found.
  1132. * Access checks are disabled on the returned constructor (if any), since
  1133. * the defining class may still be non-public.
  1134. */
  1135. private static Constructor getExternalizableConstructor(Class cl) {
  1136. try {
  1137. Constructor cons = cl.getDeclaredConstructor(new Class[0]);
  1138. cons.setAccessible(true);
  1139. return ((cons.getModifiers() & Modifier.PUBLIC) != 0) ?
  1140. cons : null;
  1141. } catch (NoSuchMethodException ex) {
  1142. return null;
  1143. }
  1144. }
  1145. /**
  1146. * Returns subclass-accessible no-arg constructor of first non-serializable
  1147. * superclass, or null if none found. Access checks are disabled on the
  1148. * returned constructor (if any).
  1149. */
  1150. private static Constructor getSerializableConstructor(Class cl) {
  1151. Class initCl = cl;
  1152. while (Serializable.class.isAssignableFrom(initCl)) {
  1153. if ((initCl = initCl.getSuperclass()) == null) {
  1154. return null;
  1155. }
  1156. }
  1157. try {
  1158. Constructor cons = initCl.getDeclaredConstructor(new Class[0]);
  1159. int mods = cons.getModifiers();
  1160. if ((mods & Modifier.PRIVATE) != 0 ||
  1161. ((mods & (Modifier.PUBLIC | Modifier.PROTECTED)) == 0 &&
  1162. !packageEquals(cl, initCl)))
  1163. {
  1164. return null;
  1165. }
  1166. cons = reflFactory.newConstructorForSerialization(cl, cons);
  1167. cons.setAccessible(true);
  1168. return cons;
  1169. } catch (NoSuchMethodException ex) {
  1170. return null;
  1171. }
  1172. }
  1173. /**
  1174. * Returns non-static, non-abstract method with given signature provided it
  1175. * is defined by or accessible (via inheritance) by the given class, or
  1176. * null if no match found. Access checks are disabled on the returned
  1177. * method (if any).
  1178. */
  1179. private static Method getInheritableMethod(Class cl, String name,
  1180. Class[] argTypes,
  1181. Class returnType)
  1182. {
  1183. Method meth = null;
  1184. Class defCl = cl;
  1185. while (defCl != null) {
  1186. try {
  1187. meth = defCl.getDeclaredMethod(name, argTypes);
  1188. break;
  1189. } catch (NoSuchMethodException ex) {
  1190. defCl = defCl.getSuperclass();
  1191. }
  1192. }
  1193. if ((meth == null) || (meth.getReturnType() != returnType)) {
  1194. return null;
  1195. }
  1196. meth.setAccessible(true);
  1197. int mods = meth.getModifiers();
  1198. if ((mods & (Modifier.STATIC | Modifier.ABSTRACT)) != 0) {
  1199. return null;
  1200. } else if ((mods & (Modifier.PUBLIC | Modifier.PROTECTED)) != 0) {
  1201. return meth;
  1202. } else if ((mods & Modifier.PRIVATE) != 0) {
  1203. return (cl == defCl) ? meth : null;
  1204. } else {
  1205. return packageEquals(cl, defCl) ? meth : null;
  1206. }
  1207. }
  1208. /**
  1209. * Returns non-static private method with given signature defined by given
  1210. * class, or null if none found. Access checks are disabled on the
  1211. * returned method (if any).
  1212. */
  1213. private static Method getPrivateMethod(Class cl, String name,
  1214. Class[] argTypes,
  1215. Class returnType)
  1216. {
  1217. try {
  1218. Method meth = cl.getDeclaredMethod(name, argTypes);
  1219. meth.setAccessible(true);
  1220. int mods = meth.getModifiers();
  1221. return ((meth.getReturnType() == returnType) &&
  1222. ((mods & Modifier.STATIC) == 0) &&
  1223. ((mods & Modifier.PRIVATE) != 0)) ? meth : null;
  1224. } catch (NoSuchMethodException ex) {
  1225. return null;
  1226. }
  1227. }
  1228. /**
  1229. * Returns true if classes are defined in the same runtime package, false
  1230. * otherwise.
  1231. */
  1232. private static boolean packageEquals(Class cl1, Class cl2) {
  1233. return (cl1.getClassLoader() == cl2.getClassLoader() &&
  1234. getPackageName(cl1).equals(getPackageName(cl2)));
  1235. }
  1236. /**
  1237. * Returns package name of given class.
  1238. */
  1239. private static String getPackageName(Class cl) {
  1240. String s = cl.getName();
  1241. int i = s.lastIndexOf('[');
  1242. if (i >= 0) {
  1243. s = s.substring(i + 2);
  1244. }
  1245. i = s.lastIndexOf('.');
  1246. return (i >= 0) ? s.substring(0, i) : "";
  1247. }
  1248. /**
  1249. * Compares class names for equality, ignoring package names. Returns true
  1250. * if class names equal, false otherwise.
  1251. */
  1252. private static boolean classNamesEqual(String name1, String name2) {
  1253. name1 = name1.substring(name1.lastIndexOf('.') + 1);
  1254. name2 = name2.substring(name2.lastIndexOf('.') + 1);
  1255. return name1.equals(name2);
  1256. }
  1257. /**
  1258. * Returns JVM type signature for given class.
  1259. */
  1260. static String getClassSignature(Class cl) {
  1261. StringBuffer sbuf = new StringBuffer();
  1262. while (cl.isArray()) {
  1263. sbuf.append('[');
  1264. cl = cl.getComponentType();
  1265. }
  1266. if (cl.isPrimitive()) {
  1267. if (cl == Integer.TYPE) {
  1268. sbuf.append('I');
  1269. } else if (cl == Byte.TYPE) {
  1270. sbuf.append('B');
  1271. } else if (cl == Long.TYPE) {
  1272. sbuf.append('J');
  1273. } else if (cl == Float.TYPE) {
  1274. sbuf.append('F');
  1275. } else if (cl == Double.TYPE) {
  1276. sbuf.append('D');
  1277. } else if (cl == Short.TYPE) {
  1278. sbuf.append('S');
  1279. } else if (cl == Character.TYPE) {
  1280. sbuf.append('C');
  1281. } else if (cl == Boolean.TYPE) {
  1282. sbuf.append('Z');
  1283. } else if (cl == Void.TYPE) {
  1284. sbuf.append('V');
  1285. } else {
  1286. throw new InternalError();
  1287. }
  1288. } else {
  1289. sbuf.append('L' + cl.getName().replace('.', '/') + ';');
  1290. }
  1291. return sbuf.toString();
  1292. }
  1293. /**
  1294. * Returns JVM type signature for given list of parameters and return type.
  1295. */
  1296. private static String getMethodSignature(Class[] paramTypes,
  1297. Class retType)
  1298. {
  1299. StringBuffer sbuf = new StringBuffer();
  1300. sbuf.append('(');
  1301. for (int i = 0; i < paramTypes.length; i++) {
  1302. sbuf.append(getClassSignature(paramTypes[i]));
  1303. }
  1304. sbuf.append(')');
  1305. sbuf.append(getClassSignature(retType));
  1306. return sbuf.toString();
  1307. }
  1308. /**
  1309. * Convenience method for throwing an exception that is either a
  1310. * RuntimeException, Error, or of some unexpected type (in which case it is
  1311. * wrapped inside an IOException).
  1312. */
  1313. private static void throwMiscException(Throwable th) throws IOException {
  1314. if (th instanceof RuntimeException) {
  1315. throw (RuntimeException) th;
  1316. } else if (th instanceof Error) {
  1317. throw (Error) th;
  1318. } else {
  1319. IOException ex = new IOException("unexpected exception type");
  1320. ex.initCause(th);
  1321. throw ex;
  1322. }
  1323. }
  1324. /**
  1325. * Returns ObjectStreamField array describing the serializable fields of
  1326. * the given class. Serializable fields backed by an actual field of the
  1327. * class are represented by ObjectStreamFields with corresponding non-null
  1328. * Field objects. Throws InvalidClassException if the (explicitly
  1329. * declared) serializable fields are invalid.
  1330. */
  1331. private static ObjectStreamField[] getSerialFields(Class cl)
  1332. throws InvalidClassException
  1333. {
  1334. ObjectStreamField[] fields;
  1335. if (Serializable.class.isAssignableFrom(cl) &&
  1336. !Externalizable.class.isAssignableFrom(cl) &&
  1337. !Proxy.isProxyClass(cl) &&
  1338. !cl.isInterface())
  1339. {
  1340. if ((fields = getDeclaredSerialFields(cl)) == null) {
  1341. fields = getDefaultSerialFields(cl);
  1342. }
  1343. Arrays.sort(fields);
  1344. } else {
  1345. fields = NO_FIELDS;
  1346. }
  1347. return fields;
  1348. }
  1349. /**
  1350. * Returns serializable fields of given class as defined explicitly by a
  1351. * "serialPersistentFields" field, or null if no appropriate
  1352. * "serialPersistentFields" field is defined. Serializable fields backed
  1353. * by an actual field of the class are represented by ObjectStreamFields
  1354. * with corresponding non-null Field objects. For compatibility with past
  1355. * releases, a "serialPersistentFields" field with a null value is
  1356. * considered equivalent to not declaring "serialPersistentFields". Throws
  1357. * InvalidClassException if the declared serializable fields are
  1358. * invalid--e.g., if multiple fields share the same name.
  1359. */
  1360. private static ObjectStreamField[] getDeclaredSerialFields(Class cl)
  1361. throws InvalidClassException
  1362. {
  1363. ObjectStreamField[] serialPersistentFields = null;
  1364. try {
  1365. Field f = cl.getDeclaredField("serialPersistentFields");
  1366. int mask = Modifier.PRIVATE | Modifier.STATIC | Modifier.FINAL;
  1367. if ((f.getModifiers() & mask) == mask) {
  1368. f.setAccessible(true);
  1369. serialPersistentFields = (ObjectStreamField[]) f.get(null);
  1370. }
  1371. } catch (Exception ex) {
  1372. }
  1373. if (serialPersistentFields == null) {
  1374. return null;
  1375. } else if (serialPersistentFields.length == 0) {
  1376. return NO_FIELDS;
  1377. }
  1378. ObjectStreamField[] boundFields =
  1379. new ObjectStreamField[serialPersistentFields.length];
  1380. Set fieldNames = new HashSet(serialPersistentFields.length);
  1381. for (int i = 0; i < serialPersistentFields.length; i++) {
  1382. ObjectStreamField spf = serialPersistentFields[i];
  1383. String fname = spf.getName();
  1384. if (fieldNames.contains(fname)) {
  1385. throw new InvalidClassException(
  1386. "multiple serializable fields named " + fname);
  1387. }
  1388. fieldNames.add(fname);
  1389. try {
  1390. Field f = cl.getDeclaredField(fname);
  1391. if ((f.getType() == spf.getType()) &&
  1392. ((f.getModifiers() & Modifier.STATIC) == 0))
  1393. {
  1394. boundFields[i] =
  1395. new ObjectStreamField(f, spf.isUnshared(), true);
  1396. }
  1397. } catch (NoSuchFieldException ex) {
  1398. }
  1399. if (boundFields[i] == null) {
  1400. boundFields[i] = new ObjectStreamField(
  1401. fname, spf.getType(), spf.isUnshared());
  1402. }
  1403. }
  1404. return boundFields;
  1405. }
  1406. /**
  1407. * Returns array of ObjectStreamFields corresponding to all non-static
  1408. * non-transient fields declared by given class. Each ObjectStreamField
  1409. * contains a Field object for the field it represents. If no default
  1410. * serializable fields exist, NO_FIELDS is returned.
  1411. */
  1412. private static ObjectStreamField[] getDefaultSerialFields(Class cl) {
  1413. Field[] clFields = cl.getDeclaredFields();
  1414. ArrayList list = new ArrayList();
  1415. int mask = Modifier.STATIC | Modifier.TRANSIENT;
  1416. for (int i = 0; i < clFields.length; i++) {
  1417. if ((clFields[i].getModifiers() & mask) == 0) {
  1418. list.add(new ObjectStreamField(clFields[i], false, true));
  1419. }
  1420. }
  1421. int size = list.size();
  1422. return (size == 0) ? NO_FIELDS :
  1423. (ObjectStreamField[]) list.toArray(new ObjectStreamField[size]);
  1424. }
  1425. /**
  1426. * Returns explicit serial version UID value declared by given class, or
  1427. * null if none.
  1428. */
  1429. private static Long getDeclaredSUID(Class cl) {
  1430. try {
  1431. Field f = cl.getDeclaredField("serialVersionUID");
  1432. int mask = Modifier.STATIC | Modifier.FINAL;
  1433. if ((f.getModifiers() & mask) == mask) {
  1434. f.setAccessible(true);
  1435. return new Long(f.getLong(null));
  1436. }
  1437. } catch (Exception ex) {
  1438. }
  1439. return null;
  1440. }
  1441. /**
  1442. * Computes the default serial version UID value for the given class.
  1443. */
  1444. private static long computeDefaultSUID(Class cl) {
  1445. if (!Serializable.class.isAssignableFrom(cl) || Proxy.isProxyClass(cl))
  1446. {
  1447. return 0L;
  1448. }
  1449. try {
  1450. ByteArrayOutputStream bout = new ByteArrayOutputStream();
  1451. DataOutputStream dout = new DataOutputStream(bout);
  1452. dout.writeUTF(cl.getName());
  1453. int classMods = cl.getModifiers() &
  1454. (Modifier.PUBLIC | Modifier.FINAL |
  1455. Modifier.INTERFACE | Modifier.ABSTRACT);
  1456. /*
  1457. * compensate for javac bug in which ABSTRACT bit was set for an
  1458. * interface only if the interface declared methods
  1459. */
  1460. Method[] methods = cl.getDeclaredMethods();
  1461. if ((classMods & Modifier.INTERFACE) != 0) {
  1462. classMods = (methods.length > 0) ?
  1463. (classMods | Modifier.ABSTRACT) :
  1464. (classMods & ~Modifier.ABSTRACT);
  1465. }
  1466. dout.writeInt(classMods);
  1467. if (!cl.isArray()) {
  1468. /*
  1469. * compensate for change in 1.2FCS in which
  1470. * Class.getInterfaces() was modified to return Cloneable and
  1471. * Serializable for array classes.
  1472. */
  1473. Class[] interfaces = cl.getInterfaces();
  1474. String[] ifaceNames = new String[interfaces.length];
  1475. for (int i = 0; i < interfaces.length; i++) {
  1476. ifaceNames[i] = interfaces[i].getName();
  1477. }
  1478. Arrays.sort(ifaceNames);
  1479. for (int i = 0; i < ifaceNames.length; i++) {
  1480. dout.writeUTF(ifaceNames[i]);
  1481. }
  1482. }
  1483. Field[] fields = cl.getDeclaredFields();
  1484. MemberSignature[] fieldSigs = new MemberSignature[fields.length];
  1485. for (int i = 0; i < fields.length; i++) {
  1486. fieldSigs[i] = new MemberSignature(fields[i]);
  1487. }
  1488. Arrays.sort(fieldSigs, new Comparator() {
  1489. public int compare(Object o1, Object o2) {
  1490. String name1 = ((MemberSignature) o1).name;
  1491. String name2 = ((MemberSignature) o2).name;
  1492. return name1.compareTo(name2);
  1493. }
  1494. });
  1495. for (int i = 0; i < fieldSigs.length; i++) {
  1496. MemberSignature sig = fieldSigs[i];
  1497. int mods = sig.member.getModifiers() &
  1498. (Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED |
  1499. Modifier.STATIC | Modifier.FINAL | Modifier.VOLATILE |
  1500. Modifier.TRANSIENT);
  1501. if (((mods & Modifier.PRIVATE) == 0) ||
  1502. ((mods & (Modifier.STATIC | Modifier.TRANSIENT)) == 0))
  1503. {
  1504. dout.writeUTF(sig.name);
  1505. dout.writeInt(mods);
  1506. dout.writeUTF(sig.signature);
  1507. }
  1508. }
  1509. if (hasStaticInitializer(cl)) {
  1510. dout.writeUTF("<clinit>");
  1511. dout.writeInt(Modifier.STATIC);
  1512. dout.writeUTF("()V");
  1513. }
  1514. Constructor[] cons = cl.getDeclaredConstructors();
  1515. MemberSignature[] consSigs = new MemberSignature[cons.length];
  1516. for (int i = 0; i < cons.length; i++) {
  1517. consSigs[i] = new MemberSignature(cons[i]);
  1518. }
  1519. Arrays.sort(consSigs, new Comparator() {
  1520. public int compare(Object o1, Object o2) {
  1521. String sig1 = ((MemberSignature) o1).signature;
  1522. String sig2 = ((MemberSignature) o2).signature;
  1523. return sig1.compareTo(sig2);
  1524. }
  1525. });
  1526. for (int i = 0; i < consSigs.length; i++) {
  1527. MemberSignature sig = consSigs[i];
  1528. int mods = sig.member.getModifiers() &
  1529. (Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED |
  1530. Modifier.STATIC | Modifier.FINAL |
  1531. Modifier.SYNCHRONIZED | Modifier.NATIVE |
  1532. Modifier.ABSTRACT | Modifier.STRICT);
  1533. if ((mods & Modifier.PRIVATE) == 0) {
  1534. dout.writeUTF("<init>");
  1535. dout.writeInt(mods);
  1536. dout.writeUTF(sig.signature.replace('/', '.'));
  1537. }
  1538. }
  1539. MemberSignature[] methSigs = new MemberSignature[methods.length];
  1540. for (int i = 0; i < methods.length; i++) {
  1541. methSigs[i] = new MemberSignature(methods[i]);
  1542. }
  1543. Arrays.sort(methSigs, new Comparator() {
  1544. public int compare(Object o1, Object o2) {
  1545. MemberSignature ms1 = (MemberSignature) o1;
  1546. MemberSignature ms2 = (MemberSignature) o2;
  1547. int comp = ms1.name.compareTo(ms2.name);
  1548. if (comp == 0) {
  1549. comp = ms1.signature.compareTo(ms2.signature);
  1550. }
  1551. return comp;
  1552. }
  1553. });
  1554. for (int i = 0; i < methSigs.length; i++) {
  1555. MemberSignature sig = methSigs[i];
  1556. int mods = sig.member.getModifiers() &
  1557. (Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED |
  1558. Modifier.STATIC | Modifier.FINAL |
  1559. Modifier.SYNCHRONIZED | Modifier.NATIVE |
  1560. Modifier.ABSTRACT | Modifier.STRICT);
  1561. if ((mods & Modifier.PRIVATE) == 0) {
  1562. dout.writeUTF(sig.name);
  1563. dout.writeInt(mods);
  1564. dout.writeUTF(sig.signature.replace('/', '.'));
  1565. }
  1566. }
  1567. dout.flush();
  1568. MessageDigest md = MessageDigest.getInstance("SHA");
  1569. byte[] hashBytes = md.digest(bout.toByteArray());
  1570. long hash = 0;
  1571. for (int i = Math.min(hashBytes.length, 8) - 1; i >= 0; i--) {
  1572. hash = (hash << 8) | (hashBytes[i] & 0xFF);
  1573. }
  1574. return hash;
  1575. } catch (IOException ex) {
  1576. throw new InternalError();
  1577. } catch (NoSuchAlgorithmException ex) {
  1578. throw new SecurityException(ex.getMessage());
  1579. }
  1580. }
  1581. /**
  1582. * Returns true if the given class defines a static initializer method,
  1583. * false otherwise.
  1584. */
  1585. private native static boolean hasStaticInitializer(Class cl);
  1586. /**
  1587. * Class for computing and caching field/constructor/method signatures
  1588. * during serialVersionUID calculation.
  1589. */
  1590. private static class MemberSignature {
  1591. public final Member member;
  1592. public final String name;
  1593. public final String signature;
  1594. public MemberSignature(Field field) {
  1595. member = field;
  1596. name = field.getName();
  1597. signature = getClassSignature(field.getType());
  1598. }
  1599. public MemberSignature(Constructor cons) {
  1600. member = cons;
  1601. name = cons.getName();
  1602. signature = getMethodSignature(
  1603. cons.getParameterTypes(), Void.TYPE);
  1604. }
  1605. public MemberSignature(Method meth) {
  1606. member = meth;
  1607. name = meth.getName();
  1608. signature = getMethodSignature(
  1609. meth.getParameterTypes(), meth.getReturnType());
  1610. }
  1611. }
  1612. /**
  1613. * Class for setting and retrieving serializable field values in batch.
  1614. */
  1615. // REMIND: dynamically generate these?
  1616. private static class FieldReflector {
  1617. /** handle for performing unsafe operations */
  1618. private static final Unsafe unsafe = Unsafe.getUnsafe();
  1619. /** fields to operate on */
  1620. private final ObjectStreamField[] fields;
  1621. /** number of primitive fields */
  1622. private final int numPrimFields;
  1623. /** unsafe field keys */
  1624. private final long[] keys;
  1625. /** field data offsets */
  1626. private final int[] offsets;
  1627. /** field type codes */
  1628. private final char[] typeCodes;
  1629. /** field types */
  1630. private final Class[] types;
  1631. /**
  1632. * Constructs FieldReflector capable of setting/getting values from the
  1633. * subset of fields whose ObjectStreamFields contain non-null
  1634. * reflective Field objects. ObjectStreamFields with null Fields are
  1635. * treated as filler, for which get operations return default values
  1636. * and set operations discard given values.
  1637. */
  1638. FieldReflector(ObjectStreamField[] fields) {
  1639. this.fields = fields;
  1640. int nfields = fields.length;
  1641. keys = new long[nfields];
  1642. offsets = new int[nfields];
  1643. typeCodes = new char[nfields];
  1644. ArrayList typeList = new ArrayList();
  1645. for (int i = 0; i < nfields; i++) {
  1646. ObjectStreamField f = fields[i];
  1647. Field rf = f.getField();
  1648. keys[i] = (rf != null) ?
  1649. unsafe.objectFieldOffset(rf) : Unsafe.INVALID_FIELD_OFFSET;
  1650. offsets[i] = f.getOffset();
  1651. typeCodes[i] = f.getTypeCode();
  1652. if (!f.isPrimitive()) {
  1653. typeList.add((rf != null) ? rf.getType() : null);
  1654. }
  1655. }
  1656. types = (Class[]) typeList.toArray(new Class[typeList.size()]);
  1657. numPrimFields = nfields - types.length;
  1658. }
  1659. /**
  1660. * Returns list of ObjectStreamFields representing fields operated on
  1661. * by this reflector. The shared/unshared values and Field objects
  1662. * contained by ObjectStreamFields in the list reflect their bindings
  1663. * to locally defined serializable fields.
  1664. */
  1665. ObjectStreamField[] getFields() {
  1666. return fields;
  1667. }
  1668. /**
  1669. * Fetches the serializable primitive field values of object obj and
  1670. * marshals them into byte array buf starting at offset 0. The caller
  1671. * is responsible for ensuring that obj is of the proper type.
  1672. */
  1673. void getPrimFieldValues(Object obj, byte[] buf) {
  1674. if (obj == null) {
  1675. throw new NullPointerException();
  1676. }
  1677. /* assuming checkDefaultSerialize() has been called on the class
  1678. * descriptor this FieldReflector was obtained from, no field keys
  1679. * in array should be equal to Unsafe.INVALID_FIELD_OFFSET.
  1680. */
  1681. for (int i = 0; i < numPrimFields; i++) {
  1682. long key = keys[i];
  1683. int off = offsets[i];
  1684. switch (typeCodes[i]) {
  1685. case 'Z':
  1686. Bits.putBoolean(buf, off, unsafe.getBoolean(obj, key));
  1687. break;
  1688. case 'B':
  1689. buf[off] = unsafe.getByte(obj, key);
  1690. break;
  1691. case 'C':
  1692. Bits.putChar(buf, off, unsafe.getChar(obj, key));
  1693. break;
  1694. case 'S':
  1695. Bits.putShort(buf, off, unsafe.getShort(obj, key));
  1696. break;
  1697. case 'I':
  1698. Bits.putInt(buf, off, unsafe.getInt(obj, key));
  1699. break;
  1700. case 'F':
  1701. Bits.putFloat(buf, off, unsafe.getFloat(obj, key));
  1702. break;
  1703. case 'J':
  1704. Bits.putLong(buf, off, unsafe.getLong(obj, key));
  1705. break;
  1706. case 'D':
  1707. Bits.putDouble(buf, off, unsafe.getDouble(obj, key));
  1708. break;
  1709. default:
  1710. throw new InternalError();
  1711. }
  1712. }
  1713. }
  1714. /**
  1715. * Sets the serializable primitive fields of object obj using values
  1716. * unmarshalled from byte array buf starting at offset 0. The caller
  1717. * is responsible for ensuring that obj is of the proper type.
  1718. */
  1719. void setPrimFieldValues(Object obj, byte[] buf) {
  1720. if (obj == null) {
  1721. throw new NullPointerException();
  1722. }
  1723. for (int i = 0; i < numPrimFields; i++) {
  1724. long key = keys[i];
  1725. if (key == Unsafe.INVALID_FIELD_OFFSET) {
  1726. continue; // discard value
  1727. }
  1728. int off = offsets[i];
  1729. switch (typeCodes[i]) {
  1730. case 'Z':
  1731. unsafe.putBoolean(obj, key, Bits.getBoolean(buf, off));
  1732. break;
  1733. case 'B':
  1734. unsafe.putByte(obj, key, buf[off]);
  1735. break;
  1736. case 'C':
  1737. unsafe.putChar(obj, key, Bits.getChar(buf, off));
  1738. break;
  1739. case 'S':
  1740. unsafe.putShort(obj, key, Bits.getShort(buf, off));
  1741. break;
  1742. case 'I':
  1743. unsafe.putInt(obj, key, Bits.getInt(buf, off));
  1744. break;
  1745. case 'F':
  1746. unsafe.putFloat(obj, key, Bits.getFloat(buf, off));
  1747. break;
  1748. case 'J':
  1749. unsafe.putLong(obj, key, Bits.getLong(buf, off));
  1750. break;
  1751. case 'D':
  1752. unsafe.putDouble(obj, key, Bits.getDouble(buf, off));
  1753. break;
  1754. default:
  1755. throw new InternalError();
  1756. }
  1757. }
  1758. }
  1759. /**
  1760. * Fetches the serializable object field values of object obj and
  1761. * stores them in array vals starting at offset 0. The caller is
  1762. * responsible for ensuring that obj is of the proper type.
  1763. */
  1764. void getObjFieldValues(Object obj, Object[] vals) {
  1765. if (obj == null) {
  1766. throw new NullPointerException();
  1767. }
  1768. /* assuming checkDefaultSerialize() has been called on the class
  1769. * descriptor this FieldReflector was obtained from, no field keys
  1770. * in array should be equal to Unsafe.INVALID_FIELD_OFFSET.
  1771. */
  1772. for (int i = numPrimFields; i < fields.length; i++) {
  1773. switch (typeCodes[i]) {
  1774. case 'L':
  1775. case '[':
  1776. vals[offsets[i]] = unsafe.getObject(obj, keys[i]);
  1777. break;
  1778. default:
  1779. throw new InternalError();
  1780. }
  1781. }
  1782. }
  1783. /**
  1784. * Sets the serializable object fields of object obj using values from
  1785. * array vals starting at offset 0. The caller is responsible for
  1786. * ensuring that obj is of the proper type; however, attempts to set a
  1787. * field with a value of the wrong type will trigger an appropriate
  1788. * ClassCastException.
  1789. */
  1790. void setObjFieldValues(Object obj, Object[] vals) {
  1791. if (obj == null) {
  1792. throw new NullPointerException();
  1793. }
  1794. for (int i = numPrimFields; i < fields.length; i++) {
  1795. long key = keys[i];
  1796. if (key == Unsafe.INVALID_FIELD_OFFSET) {
  1797. continue; // discard value
  1798. }
  1799. switch (typeCodes[i]) {
  1800. case 'L':
  1801. case '[':
  1802. Object val = vals[offsets[i]];
  1803. if (val != null &&
  1804. !types[i - numPrimFields].isInstance(val))
  1805. {
  1806. Field f = fields[i].getField();
  1807. throw new ClassCastException(
  1808. "cannot assign instance of " +
  1809. val.getClass().getName() + " to field " +
  1810. f.getDeclaringClass().getName() + "." +
  1811. f.getName() + " of type " +
  1812. f.getType().getName() + " in instance of " +
  1813. obj.getClass().getName());
  1814. }
  1815. unsafe.putObject(obj, key, val);
  1816. break;
  1817. default:
  1818. throw new InternalError();
  1819. }
  1820. }
  1821. }
  1822. }
  1823. /**
  1824. * Matches given set of serializable fields with serializable fields
  1825. * described by the given local class descriptor, and returns a
  1826. * FieldReflector instance capable of setting/getting values from the
  1827. * subset of fields that match (non-matching fields are treated as filler,
  1828. * for which get operations return default values and set operations
  1829. * discard given values). Throws InvalidClassException if unresolvable
  1830. * type conflicts exist between the two sets of fields.
  1831. */
  1832. private static FieldReflector getReflector(ObjectStreamField[] fields,
  1833. ObjectStreamClass localDesc)
  1834. throws InvalidClassException
  1835. {
  1836. // class irrelevant if no fields
  1837. Class cl = (localDesc != null && fields.length > 0) ?
  1838. localDesc.cl : null;
  1839. Object key = new FieldReflectorKey(cl, fields);
  1840. Object entry;
  1841. EntryFuture future = null;
  1842. synchronized (reflectors) {
  1843. if ((entry = reflectors.get(key)) == null) {
  1844. reflectors.put(key, future = new EntryFuture());
  1845. }
  1846. }
  1847. if (entry instanceof FieldReflector) { // check common case first
  1848. return (FieldReflector) entry;
  1849. } else if (entry instanceof EntryFuture) {
  1850. entry = ((EntryFuture) entry).get();
  1851. } else if (entry == null) {
  1852. try {
  1853. entry = new FieldReflector(matchFields(fields, localDesc));
  1854. } catch (Throwable th) {
  1855. entry = th;
  1856. }
  1857. future.set(entry);
  1858. synchronized (reflectors) {
  1859. reflectors.put(key, entry);
  1860. }
  1861. }
  1862. if (entry instanceof FieldReflector) {
  1863. return (FieldReflector) entry;
  1864. } else if (entry instanceof InvalidClassException) {
  1865. throw (InvalidClassException) entry;
  1866. } else if (entry instanceof RuntimeException) {
  1867. throw (RuntimeException) entry;
  1868. } else if (entry instanceof Error) {
  1869. throw (Error) entry;
  1870. } else {
  1871. throw new InternalError("unexpected entry: " + entry);
  1872. }
  1873. }
  1874. /**
  1875. * FieldReflector cache lookup key. Keys are considered equal if they
  1876. * refer to the same class and equivalent field formats.
  1877. */
  1878. private static class FieldReflectorKey {
  1879. private final Class cl;
  1880. private final String sigs;
  1881. private final int hash;
  1882. FieldReflectorKey(Class cl, ObjectStreamField[] fields) {
  1883. /*
  1884. * Note: maintaining a direct reference to the class does not pin
  1885. * it indefinitely, since SoftCache removes strong refs to keys
  1886. * when the corresponding values are gc'ed.
  1887. */
  1888. this.cl = cl;
  1889. StringBuffer sbuf = new StringBuffer();
  1890. for (int i = 0; i < fields.length; i++) {
  1891. ObjectStreamField f = fields[i];
  1892. sbuf.append(f.getName()).append(f.getSignature());
  1893. }
  1894. sigs = sbuf.toString();
  1895. hash = System.identityHashCode(cl) + sigs.hashCode();
  1896. }
  1897. public int hashCode() {
  1898. return hash;
  1899. }
  1900. public boolean equals(Object obj) {
  1901. if (!(obj instanceof FieldReflectorKey)) {
  1902. return false;
  1903. }
  1904. FieldReflectorKey key = (FieldReflectorKey) obj;
  1905. return (cl == key.cl && sigs.equals(key.sigs));
  1906. }
  1907. }
  1908. /**
  1909. * Matches given set of serializable fields with serializable fields
  1910. * obtained from the given local class descriptor (which contain bindings
  1911. * to reflective Field objects). Returns list of ObjectStreamFields in
  1912. * which each ObjectStreamField whose signature matches that of a local
  1913. * field contains a Field object for that field; unmatched
  1914. * ObjectStreamFields contain null Field objects. Shared/unshared settings
  1915. * of the returned ObjectStreamFields also reflect those of matched local
  1916. * ObjectStreamFields. Throws InvalidClassException if unresolvable type
  1917. * conflicts exist between the two sets of fields.
  1918. */
  1919. private static ObjectStreamField[] matchFields(ObjectStreamField[] fields,
  1920. ObjectStreamClass localDesc)
  1921. throws InvalidClassException
  1922. {
  1923. ObjectStreamField[] localFields = (localDesc != null) ?
  1924. localDesc.fields : NO_FIELDS;
  1925. /*
  1926. * Even if fields == localFields, we cannot simply return localFields
  1927. * here. In previous implementations of serialization,
  1928. * ObjectStreamField.getType() returned Object.class if the
  1929. * ObjectStreamField represented a non-primitive field and belonged to
  1930. * a non-local class descriptor. To preserve this (questionable)
  1931. * behavior, the ObjectStreamField instances returned by matchFields
  1932. * cannot report non-primitive types other than Object.class; hence
  1933. * localFields cannot be returned directly.
  1934. */
  1935. ObjectStreamField[] matches = new ObjectStreamField[fields.length];
  1936. for (int i = 0; i < fields.length; i++) {
  1937. ObjectStreamField f = fields[i], m = null;
  1938. for (int j = 0; j < localFields.length; j++) {
  1939. ObjectStreamField lf = localFields[j];
  1940. if (f.getName().equals(lf.getName())) {
  1941. if ((f.isPrimitive() || lf.isPrimitive()) &&
  1942. f.getTypeCode() != lf.getTypeCode())
  1943. {
  1944. throw new InvalidClassException(localDesc.name,
  1945. "incompatible types for field " + f.getName());
  1946. }
  1947. if (lf.getField() != null) {
  1948. m = new ObjectStreamField(
  1949. lf.getField(), lf.isUnshared(), false);
  1950. } else {
  1951. m = new ObjectStreamField(
  1952. lf.getName(), lf.getSignature(), lf.isUnshared());
  1953. }
  1954. }
  1955. }
  1956. if (m == null) {
  1957. m = new ObjectStreamField(
  1958. f.getName(), f.getSignature(), false);
  1959. }
  1960. m.setOffset(f.getOffset());
  1961. matches[i] = m;
  1962. }
  1963. return matches;
  1964. }
  1965. }