Slide 10.1 Advanced Programming 2004, based on LY Stefanus’s Slides Object Serialization Object serialization: the process of converting an object into.

Slides:



Advertisements
Similar presentations
A Guide to Advanced Java Faculty:Nguyen Ngoc Tu. 2 Operating System Application #1 Application #2 Java Virtual Machine #1 Local Memory Shared Memory Threads.
Advertisements

Lecture 5: Interfaces.
Lecture 15: I/O and Parsing
The Package Statement Group related interfaces and classes together Purpose: encapsulation and reduces name conflicts –private package classes not visible.
Java File I/O. File I/O is important! Being able to write and read from files is necessary and is also one common practice of a programmer. Examples include.
MOD III. Input / Output Streams Byte streams Programs use byte streams to perform input and output of 8-bit bytes. This Stream handles the 8-bit.
Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.
Streams Dwight Deugo Nesa Matic Portions of the notes for this lecture include excerpts from.
Spring/2002 Distributed Software Engineering C:\unocourses\4350\slides\DefiningThreads 1 Serialization Flatten your object for automated storage or network.
CSC 243 – Java Programming, Spring 2013 March 26, 2013 Week 8, java.lang.Clonable & java.io.Serializable Interfaces.
Class Hierarchy II Discussion E. Hierarchy A mail order business sells catalog merchandise all over the country. The rules for taxation on the merchandise.
Geoff Holmes Overview IO Zoo Stream I/O File I/O Buffering Random-Access Text Streams Examples Serialization Java IO – programs that start with import.
1 Chapter 8 Three Interfaces: Cloneable, Serializable, and Runnable.
Object Serialization in Java Or: The Persistence of Memory…
Java Iterators interface Collection { … Iterator iterator(); Iterator iterator(); …} interface Set extends Collection { … Iterator iterator(); Iterator.
1 Chapter 7 Inheritance, Polymorphism, and Scope.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 18 Binary I/O.
1 Chapter 2 Introductory Programs. 2 Getting started To create and run a Java program –Create a text file with a.java extension for the source code. For.
Scott Grissom, copyright 2004Ch 3: Java Features Slide 1 Why Java? It is object-oriented provides many ready to use classes platform independent modern.
Advanced Java Class Serialization. Serialization – what and why? What? –Translating the contents of an Object to a series of bytes that represent it,
1 Java object model Part 3: Serialization & Reflection.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L08 (Chapter 18) Binary I/O.
Files and Streams (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
Software Design 13.1 XML: Another TLA or the Future? XML is eXtensible Markup Language  It's a w3c standard.
Streams Reading: 2 nd Ed: , rd Ed: 11.1, 19.1, 19.4
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Java I/O Writing and Reading Objects to File Serialization.
Object Persistence and Object serialization CSNB534 Asma Shakil.
Java Programming: Advanced Topics 1 Input/Output and Serialization Chapter 3.
Object Serialization.  When the data was output to disk, certain information was lost, such as the type of each value.  If the value "3" is read from.
Outline  Basic IO  File class  The Stream Zoo  Serialization  Regular Expressions.
Serialization CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
©SoftMoore ConsultingSlide 1 Serialization. ©SoftMoore ConsultingSlide 2 Serialization Allows objects to be written to a stream Can be used for persistence.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
1 Chapter 19 Binary I/O. 2 Motivations F Data stored in a text file – is represented in human-readable form –Text file –Readable –Java source programs.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Interfaces F What is an Interface? F Creating an Interface F Implementing an Interface F What is Marker Interface?
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 12 GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology/ George Koutsogiannakis 1.
The Prototype Pattern (Creational) ©SoftMoore ConsultingSlide 1.
Introduction to Collections. Collections Collections provide a way of organizing related data in a model Different types of collections have different.
Spring 2008 Mark Fontenot CSE Honors Principles of Computer Science I Note Set 20.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 13 Java Fundamentals File I/O Serializing an.
1 Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
1 Copyright © 2011 Tata Consultancy Services Limited TCS Internal.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Files and Serialization. Files Used to transfer data to and from secondary storage.
File Input & Output1 Streams & File I/O. Introduction (1) The Java platform includes a number of packages that are concerned with the movement of data.
Java Programming: Advanced Topics 1 Input/Output and Serialization.
1 CSE 331 Memento Pattern and Serialization slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
OBJECT ORIENTED PROGRAMMING II LECTURE 21 GEORGE KOUTSOGIANNAKIS
Object Writing in files
Memento Design Pattern
Chapter 17 Binary I/O 1.
Accessing Files in Java
Java Serialization B.Ramamurthy 11/8/2018 B.Ramamurthy.
Java Serialization B.Ramamurthy 11/14/2018 B.Ramamurthy.
Persistence & Bean Properties
Java Programming Language
The Building Blocks Classes: Java class library, over 1,800 classes:
Serialization and Deserialization Bullet points from Head First Java, Ch Dec-18 serialization.ppt.
CSE 331 Memento Pattern slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
OBJECT ORIENTED PROGRAMMING II LECTURE 22 GEORGE KOUTSOGIANNAKIS
Podcast Ch23f Title: Serialization
The command invocation protocol
System Models Bina Ramamurthy 9/7/2019 B.Ramamurthy.
OO Java Programming Input Output.
Presentation transcript:

slide 10.1 Advanced Programming 2004, based on LY Stefanus’s Slides Object Serialization Object serialization: the process of converting an object into a stream of bytes.

slide 10.2 Advanced Programming 2004, based on LY Stefanus’s Slides Where to use as the basis for transfering objects via cut-and-paste. (Alternative: MIME type string, see page. 162 JiaN) to transfer objects between a client and a server for remote method invocation (RMI). Pre-initialized java beans, persistent java beans Pre-initialized applets Save user preferences and application state – a serialized object is an instant file format that works for any application. GUI Builder Tools, saving complete hierarchy Component hierarchy. OS, hibernate (e.g. Windows XP)

slide 10.3 Advanced Programming 2004, based on LY Stefanus’s Slides Serialization Object serialization: the process of converting an object into a stream of bytes. writeObject() Object deserialization: the process of converting a stream of bytes back into a copy of the original object. readObject() An object of any class that implements the java.io.Serializable interface can be saved and restored from a stream of bytes. Special stream classes from the package java.io, ObjectInputStream and ObjectOutputStream, are used to serialize primitive types and objects. Subclasses of Serializable classes are also serializable.

slide 10.4 Advanced Programming 2004, based on LY Stefanus’s Slides java.io.Serializable is an example of marker interface. Marker interface is an interface that is entirely empty. A class can implement this interface simply by naming it in its implements clause without having to implement any methods. We can check whether an object is an instance of the interface using the instanceof operator, so this technique is a useful way to provide additional information about an object. Another example of marker interface is java.lang.Cloneable.

slide 10.5 Advanced Programming 2004, based on LY Stefanus’s Slides The default serialization mechanism saves the value of an object's nonstatic and nontransient member variables. When an object is serialized, any object references that it contains are also serialized. The implication is that any object we serialize must contain only references to other Serializable objects. We can take control by marking nonserializable members as transient or overriding the default serialization mechanisms. The transient modifier can be applied to any instance variable to indicate that its contents are not useful outside of the current context and should never be saved or serialized. See the examples: Save.java, Load.java

slide 10.6 Advanced Programming 2004, based on LY Stefanus’s Slides Save.java //Create a hashtable and write (serialize) it to a file called h.ser //The Hashtable object is serializable because it implements //the Serializable interface. import java.io.*; import java.util.*; public class Save { public static void main(String[] args) { Hashtable h = new Hashtable(); h.put("harry", "Harry Potter"); h.put("satu", new Integer(1)); h.put("pi", new Double(Math.PI)); try { FileOutputStream fos = new FileOutputStream("h.ser"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(h); } catch (Exception e) { System.err.println(e); }

slide 10.7 Advanced Programming 2004, based on LY Stefanus’s Slides Load.java //Read (deserialize) the hashtable from the h.ser file. import java.io.*; import java.util.*; public class Load { public static void main(String[] args) { try { FileInputStream fis = new FileInputStream("h.ser"); ObjectInputStream ois = new ObjectInputStream(fis); Hashtable h = (Hashtable) ois.readObject(); System.out.println(h.get("harry"));//print: Harry Potter System.out.println(h.get("satu"));//print: 1 } catch (Exception e) { System.err.println(e); }

slide 10.8 Advanced Programming 2004, based on LY Stefanus’s Slides Class Versioning When an object is serialized, some information about its class must obviously be serialized with it, so that the correct class file cab be loaded when the object is deserialized. The information about the class is represented by the : Java.io.ObjectStreamClass. It contains the fully qualified name of the class and a version number. Static final long serialVersionUID = L; To compute an initial value use JDK: serialver

slide 10.9 Advanced Programming 2004, based on LY Stefanus’s Slides Custom Serialization Example 9-2 (page 175 JiaN2) // This example is from the book "Java in a Nutshell, Second Edition". // Written by David Flanagan. Copyright (c) 1997 O'Reilly & Associates. // You may distribute this source code for non-commercial purposes only. // You may study, modify, and use this example for any purpose, as long as // this notice is retained. Note that this example is provided "as is", // WITHOUT WARRANTY of any kind either expressed or implied. import java.io.*; /** A simple class that implements a growable array or ints, and knows * how to serialize itself as efficiently as a non-growable array. */ public class IntList implements Serializable {

slide Advanced Programming 2004, based on LY Stefanus’s Slides private int[] nums = new int[8]; // An array to store the numbers. private transient int size = 0; // Index of next unused element of nums[]. /** Return an element of the array */ public int elementAt(int index) throws ArrayIndexOutOfBoundsException { if (index >= size) throw new ArrayIndexOutOfBoundsException(index); else return nums[index]; } /** Add an int to the array, growing the array if necessary */ public void add(int x) { if (nums.length == size) resize(nums.length*2); // Grow array, if needed. nums[size++] = x; // Store the int in it. }

slide Advanced Programming 2004, based on LY Stefanus’s Slides /** An internal method to change the allocated size of the array */ protected void resize(int newsize) { int[] oldnums = nums; nums = new int[newsize]; // Create a new array. System.arraycopy(oldnums, 0, nums, 0, size); // Copy array elements. } /** Get rid of unused array elements before serializing the array */ private void writeObject(ObjectOutputStream out) throws IOException { if (nums.length > size) resize(size); // Compact the array. out.defaultWriteObject(); // Then write it out normally. } /** Compute the transient size field after deserializing the array */ private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); // Read the array normally. size = nums.length; // Restore the transient field. }

slide Advanced Programming 2004, based on LY Stefanus’s Slides Serialized Applets <APPLET OBJECT = ”MyApplet.ser” WIDTH=400 HEIGHT=200> Use Appletviewer.

slide Advanced Programming 2004, based on LY Stefanus’s Slides JavaBeans Persistence Java 1.4 introduces a new serialization mechanism intended for use with JavaBeans. Java.io serialization works by saving the state of an object as a sequence of bytes in binary format. Java.beans persistence works by saving the state of an object or a bean as a sequence of calls to the public methods defined by the class, in XML format. Since JavaBeans persistence is based on the public API rather than on the internal state, its mechanism allows interoperability between different implementations of the same API, and is suitable for longer-term storage of serialized objects.

slide Advanced Programming 2004, based on LY Stefanus’s Slides JavaBeans Persistence (cont.) A bean or other objects can be serialized with java.beans.XMLEncoder and can be deserialized with java.beans.XMLDecoder. These classes write to and read from specified streams, but they are not stream classes themselves. See the examples: SaveXML.java, LoadXML.java

slide Advanced Programming 2004, based on LY Stefanus’s Slides SaveXML.java //Create a hashtable and write (serialize) it to a file called h.xml import java.io.*; import java.util.*; import java.beans.*; public class SaveXML { public static void main(String[] args) { Hashtable h = new Hashtable(); h.put("harry", "Harry Potter"); h.put("satu", new Integer(1)); h.put("pi", new Double(Math.PI)); try { FileOutputStream fos = new FileOutputStream("h.xml"); XMLEncoder enc = new XMLEncoder(fos); enc.writeObject(h); enc.close(); } catch (Exception e) { System.err.println(e); }

slide Advanced Programming 2004, based on LY Stefanus’s Slides h.xml harry Harry Potter pi satu 1

slide Advanced Programming 2004, based on LY Stefanus’s Slides LoadXML.java //Read (deserialize) the hashtable from the h.XML file. import java.io.*; import java.util.*; import java.beans.*; public class LoadXML { public static void main(String[] args) { try { FileInputStream fis = new FileInputStream("h.xml"); XMLDecoder dec = new XMLDecoder(fis); Hashtable h = (Hashtable) dec.readObject(); System.out.println(h.get("harry"));//print: Harry Potter System.out.println(h.get("satu"));//print: 1 } catch (Exception e) { System.err.println(e); }

slide Advanced Programming 2004, based on LY Stefanus’s Slides Advanced Serialization: Externalizable Only the identity of the class of an Externalizable instance is written in the serialization stream. It is the responsibility of the class to save and restore the contents of its instances, and it must coordinate with its superclasses to do so. Each object to be stored is tested for the Externalizable interface. If the object supports Externalizable, the writeExternal method is called. If the object does not support Externalizable and does implement Serializable, the object is saved using ObjectOutputStream.

slide Advanced Programming 2004, based on LY Stefanus’s Slides Externalizable Here's the complete definition of the Externalizable interface that extends Serializable: package java.io; public interface Externalizable extends Serializable { public void writeExternal(ObjectOutput out) throws IOException; public void readExternal(ObjectInput in) throws IOException, java.lang.ClassNotFoundException; }

slide Advanced Programming 2004, based on LY Stefanus’s Slides What holds for an Externalizable class? It must implement the java.io.Externalizable interface. It must implement a writeExternal method to save the state of the object. Also, it must explicitly coordinate with its supertype to save its state. It must implement a readExternal method to read the data written by the writeExternal method from the stream and restore the state of the object. It must explicitly coordinate with the supertype to restore its state. If externally defined format is being written, the writeExternal and readExternal methods are solely responsible for that format.