Java object model Part 3 Serialization Reflection 1
Java object model Part 3: Serialization & Reflection 1
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 2
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 write. Object() method of the Object. Output. Stream class; to deserialize, invoke the read. Object() method of Object. Input. Stream 3
Example // write data to output file: My. Class[] students = new My. Class[12]; . . . Object. Output. Stream outs = new Object. Output. Stream (new File. Output. Stream(“myfile. dat”)); outs. write. Object(students); outs. close(); // read data from input file: Object. Input. Stream ins = new Object. Input. Stream (new File. Input. Stream(“myfile. dat”)); My. Class students = (My. Class[]) ins. read. Object(); ins. close(); 4
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 5
Standard Java classes & serialization • Many standard classes implement Serializable • Examples: – String – Array. List: means entire list of objects could be stored in a single operation 6
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 7
Reflection • Mechanism by which a program can analyze its objects & their capabilities at runtime • Java API includes several reflection classes, classes described on next slide 8
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 9
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 10
Class class methods • get. Super. Class() returns Class object that describes superclass of a given type; returns null is type is Object or is not a class • get. Interfaces() 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) 11
Class class methods • get. Package() returns Package object; Package has get. Name() method which returns String containing package name • get. Declared. Fields() returns array of Field objects declared by this class or interface – includes public, private, protected & packagevisible fields – includes both static & instance fields – does not include superclass fields 12
Field class methods • get. Name(): returns String containing field name • get. Type(): returns Class describing field type • get. Modifiers(): returns an int whose various bits are set to indicate whether field is public, private, protected, static, or final: use static Modifier methods is. Public, is. Private, is. Protected, is. Static, is. Final to test this value 13
Example - prints all static fields of java. lang. Math Field[] fields = math. class. get. Declared. Fields(); for (int x = 0; x < fields. length; x++) if(Modifier. is. Static(fields[x]. get. Modifiers())) System. out. println(fields[x]. get. Name()); 14
More Class class methods • get. Declared. Constructors() returns array of Constructor objects describing class constructors • Constructor object has method get. Parameter. Types that returns an array of Class objects describing the constructor’s parameters 15
Example: printing Rectangle constructor information Constructor cons = Rectangle. class. get. Declared. Constructors(); for (int=0; x < cons. length; x++) { Class [] params = cons[x]. get. Parameter. Types(); System. out. println(“Rectangle(”); for (int y=0; y < params. length; y++) { if(y > 0) System. out. print(“, ”); System. out. print(params[y]. get. Name()); } System. out. println(“)”); } 16
Output from example Rectangle() Rectangle(java. awt. Rectangle) Rectangle(int, int) Rectangle(java. awt. Point, java. awt. Dimension) Rectangle(java. awt. Point) Rectangle(java. awt. Dimension) 17
Class class’s get. Declared. Methods() method • Returns array of Method objects • Method object methods include: – get. Parameter. Types(): returns array of parameter types – get. Name(): returns method name – get. Return. Type(): returns Class object describing return value type 18
Obtaining single Method or Constructor objects • Class’s get. Declared. Method() (note the singular) returns a Method object if supplied with a method name and array of parameter objects: Method m = Rectangle. class. get. Declared. Method(“contains”, new Class[]{int. class, int. class}); • For Constructor object: Constructor c = Rectangle. class. get. Declared. Constructor(new Class[] {}); 19
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 20
Example - saying hello the hard way import java. lang. reflect. *; import java. io. *; public class Say. Hello { public static void main(String[]args) throws No. Such. Method. Exception, Illegal. Access. Exception, Invocation. Target. Exception { Method m = Print. Stream. class. get. Declared. Method (“println”, new Class[] {String. class}); m. invoke(System. out, new Object[] {“Hello!}); } } 21
Example with return value Method m = Math. class. get. Declared. Method(“sqrt”, new Class[] {double. class}); Object r = m. invoke(null, new Object[] {new Double(10. 24)}); double x = ((Double) r). double. Value(); 22
Inspecting objects • Can use reflection mechanism to dynamically look up object fields as program runs • To allow access to a field, call its set. Accessible() method; example: Class c = object. get. Class(); Field f = c. get. Declared. Field(name); f. set. Accessible(true); 23
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 24
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); 25
Inspecting array elements • Finding length of array a: int n = Array. get. Length(a); • Creating new array (twice as large) with static method new. Instance(): Object new. Array = Array. new. Instance( a. get. Class(). get. Component. Type(), 2 * Array. get. Length(a) + 1); System. arraycopy(a, 0, new. Array, 0, Array. get. Length(a)); a = new. Array; 26
- Slides: 26