FileDocCategorySizeDatePackage
Substitute.javaAPI DocExample4871Wed Apr 19 11:21:24 BST 2000None

Substitute

public class Substitute extends Object
This example shows how to use the readResolve method. This method resolves the object read from the stream before it is returned to the caller. The writeReplacea method allows an object to nominate its own replacement in the stream before the object is written. This example creates a symbol class for which only a single instance of each symbol binding exists. The Symbol class defines the readResolve method. A symbol is created from outside using the symbollookup method, which finds and returns a symbol if one already exists and creates one, if one does not. This assures uniqueness within one VM. Then, when readResolve is called when the symbol is being read, a preexisting equivalent Symbol object is substituted from the hashtable to maintain the unique identity constraint, if such a symbol exists. Otherwise, the new symbol is added to the hashtable and returned. This assures uniqueness when we are dealing with more than one VM. How to Run: Compile this file: javac Substitute.java Run this file: java Substitute This will print out a confirmation that the two symbols that were serialized separately but had the same name are indeed the same symbol. Compiled and Tested with JDK1.2

Fields Summary
Constructors Summary
Methods Summary
public static voidmain(java.lang.String[] args)
Basically, serialize and deserialize two symbols with the same name and show that they are actually the same symbol.

	
	// create a few symbols to be serialized
	Symbol s1 = Symbol.symbolLookup("blue");
	Symbol s2 = Symbol.symbolLookup("pink");
	Symbol s3 = Symbol.symbolLookup("blue");

	// use these to deserialize the symbols
	Symbol obj1 = null, obj2 = null, obj3 = null;


	// serialize the symbols
	try {
 	    FileOutputStream fo = new FileOutputStream("symbol.tmp");
	    ObjectOutputStream so = new ObjectOutputStream(fo);
	    so.writeObject(s1);
	    so.writeObject(s2);
	    so.writeObject(s3);
	    so.flush();
	} catch (Exception e) {
	    System.out.println(e);
	    System.exit(1);
	}
	
	// deserialize the symbols
	try {
	    FileInputStream fi = new FileInputStream("symbol.tmp");
	    ObjectInputStream si = new ObjectInputStream(fi);
	    obj1 = (Symbol) si.readObject();
	    obj2 = (Symbol) si.readObject();
	    obj3 = (Symbol) si.readObject();
	} catch (Exception e) {
	    System.out.println(e);
	    System.exit(1);
	}

	// show the uniqueness 
	if (obj1 == obj3) {
	    System.out.println("Symbol1 and Symbol3 are the same!");
	}