Download Java object model

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
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 writeObject()
method of the ObjectOutputStream class; to
deserialize, invoke the readObject() method of
ObjectInputStream
3
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();
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
– ArrayList: 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,
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
• 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)
11
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 & packagevisible fields
– includes both static & instance fields
– does not include superclass fields
12
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
13
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());
14
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
15
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(“)”);
}
16
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)
17
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
18
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[] {});
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 SayHello
{
public static void main(String[]args) throws
NoSuchMethodException, IllegalAccessException,
InvocationTargetException
{
Method m = PrintStream.class.getDeclaredMethod
(“println”, new Class[] {String.class});
m.invoke(System.out, new Object[] {“Hello!});
}
}
21
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();
22
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);
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.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;
26