View
237
Download
1
Embed Size (px)
Citation preview
2
Serialization
• Denotes the process of storing an object to a stream without converting to an external representataion
• Serialization allows an object to be persistent: that is, to exist separate from the program that created it
• When an object is serialized, it is transformed into a sequence of bytes; this can later be restored to the original object
3
Java object serialization
• In order for an object to be serialized, it must implement the Serializable interface
• Like Cloneable, Serializable is devoid of methods• To serialize an object, invoke the writeObject()
method of the ObjectOutputStream class; to deserialize, invoke the readObject() method of ObjectInputStream
4
Example// write data to output file:MyClass[] students = new MyClass[12];...ObjectOutputStream outs = new ObjectOutputStream
(new FileOutputStream(“myfile.dat”));outs.writeObject(students);outs.close();
// read data from input file:ObjectInputStream ins = new ObjectInputStream
(new FileInputStream(“myfile.dat”));MyClass students = (MyClass[]) ins.readObject();ins.close();
5
Serialization & dependent objects
• Serialization automatically takes into account any additional referenced objects - follows all references contained in the object being serialized & serializes them
• Thus, any objects contained within a serializable object must also implement Serializable
6
Standard Java classes & serialization
• Many standard classes implement Serializable
• Examples:– String– ArrayList: means entire list of objects could be
stored in a single operation
7
The transient modifier
• We may wish to exclude some information when serializing an object:– passwords or other confidential data– extraneous data (whether or not a particular
graphical object was in a selected state, e.g.)
• Reserved word transient can be used to modify variable declaration; such a variable will not be represented when the object is serialized
8
Reflection
• Mechanism by which a program can analyze its objects & their capabilities at runtime
• Java API includes several reflection reflection classesclasses, described on next slide
9
Reflection Classes
• Class: describes a type• Package: describes a package• Field: describes field; allows inspection,
modification of all fields• Method: describes method, allows its invocation on
objects• Constructor: describes constructor, allows its
invocation• Array: has static methods to analyze arrays
10
Class class object
• Includes class name and superclass of an object, as we have already seen; also includes:– interface types class implements– package of class– names & types of all fields– names, parameter types, return types of all
methods– parameter types of all constructors
11
Class class methods
• getSuperClass() returns Class object that describes superclass of a given type; returns null is type is Object or is not a class
• getInterfaces() returns array of Class objects describing interface types implemented or extended; if type doesn’t implement or extend any interfaces, returns array of length 0 (only returns direct superinterfaces)
12
Class class methods
• getPackage() returns Package object; Package has getName() method which returns String containing package name
• getDeclaredFields() returns array of Field objects declared by this class or interface– includes public, private, protected & package-visible
fields– includes both static & instance fields– does not include superclass fields
13
Field class methods
• getName(): returns String containing field name• getType(): returns Class describing field type• getModifiers(): returns an int whose various bits
are set to indicate whether field is public, private, protected, static, or final: use static Modifier methods isPublic, isPrivate, isProtected, isStatic, isFinal to test this value
14
Example - prints all static fields of java.lang.Math
Field[] fields = math.class.getDeclaredFields();for (int x = 0; x < fields.length; x++)
if(Modifier.isStatic(fields[x].getModifiers()))System.out.println(fields[x].getName());
15
More Class class methods
• getDeclaredConstructors() returns array of Constructor objects describing class constructors
• Constructor object has method getParameterTypes that returns an array of Class objects describing the constructor’s parameters
16
Example: printing Rectangle constructor information
Constructor cons = Rectangle.class.getDeclaredConstructors();for (int=0; x < cons.length; x++){
Class [] params = cons[x].getParameterTypes();System.out.println(“Rectangle(”);for (int y=0; y < params.length; y++){
if(y > 0) System.out.print(“, ”);System.out.print(params[y].getName());
}System.out.println(“)”);
}
17
Output from example
Rectangle()Rectangle(java.awt.Rectangle)Rectangle(int, int, int, int)Rectangle(int, int)Rectangle(java.awt.Point, java.awt.Dimension)Rectangle(java.awt.Point)Rectangle(java.awt.Dimension)
18
Class class’s getDeclaredMethods() method
• Returns array of Method objects
• Method object methods include:– getParameterTypes(): returns array of
parameter types– getName(): returns method name– getReturnType(): returns Class object
describing return value type
19
Obtaining single Method or Constructor objects
• Class’s getDeclaredMethod() (note the singular) returns a Method object if supplied with a method name and array of parameter objects:Method m = Rectangle.class.getDeclaredMethod(“contains”, new
Class[]{int.class, int.class});
• For Constructor object:Constructor c = Rectangle.class.getDeclaredConstructor(new
Class[] {});
20
Method methods
• invoke(): can be used to call a method described by a Method object - need to:– supply implicit parameter (null for static
methods)– supply array of explicit parameter values (need
to wrap primitive types)– if method returns a value, invoke returns an
Object; need to cast or unwrap return value, as appropriate
21
Example - saying hello the hard wayimport java.lang.reflect.*;import java.io.*;public class SayHello{
public static void main(String[]args) throwsNoSuchMethodException, IllegalAccessException,
InvocationTargetException{
Method m = PrintStream.class.getDeclaredMethod(“println”, new Class[] {String.class});m.invoke(System.out, new Object[] {“Hello!});
}}
22
Example with return value
Method m = Math.class.getDeclaredMethod(“sqrt”, new Class[] {double.class});
Object r = m.invoke(null, new Object[] {new Double(10.24)});double x = ((Double) r).doubleValue();
23
Inspecting objects
• Can use reflection mechanism to dynamically look up object fields as program runs
• To allow access to a field, call its setAccessible() method; example:Class c = object.getClass();
Field f = c.getDeclaredField(name);
f.setAccessible(true);
24
Inspecting objects
• Once granted access, you can read and write any field of the object:Object value = f.get(object);
f.set(object, value);
• Notes: – f must be a Field that describes a field of object;
otherwise, get and set throw exception
– if field type is primitive, get returns & set expects a wrapper
– if field is static, supply null for object
25
Inspecting array elements
• Field allows read/write access to arbitrary field of object; Array works similarly on array objects– for array a with index x:– get() method: Object value = Array.get(a,x)– set() method: Array.set(a,x,value);
26
Inspecting array elements
• Finding length of array a:int n = Array.getLength(a);
• Creating new array (twice as large) with static method newInstance():
Object newArray = Array.newInstance(a.getClass().getComponentType(),2 * Array.getLength(a) + 1);
System.arraycopy(a, 0, newArray, 0, Array.getLength(a));a = newArray;