1 Java object model Part 3: Serialization & Reflection.

Slides:



Advertisements
Similar presentations
Chapter 1 Object-Oriented Concepts. A class consists of variables called fields together with functions called methods that act on those fields.
Advertisements

Streams Dwight Deugo Nesa Matic Portions of the notes for this lecture include excerpts from.
INHERITANCE BASICS Reusability is achieved by INHERITANCE
Reflection Reflection is the ability of a program to examine and modify the structure and behavior of an object at runtime.
METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.
Spring/2002 Distributed Software Engineering C:\unocourses\4350\slides\DefiningThreads 1 Serialization Flatten your object for automated storage or network.
Slide 10.1 Advanced Programming 2004, based on LY Stefanus’s Slides Object Serialization Object serialization: the process of converting an object into.
Methods. int month; int year class Month Defining Classes A class contains data declarations (static and instance variables) and method declarations (behaviors)
Slide 11.1 Advanced Programming 2004, based on LY Stefanus’s Slides Reflection Reflection is the ability for a class or object to examine itself. Java.
JAVA: An Introduction to Problem Solving & Programming, 7 th Ed. By Walter Savitch ISBN © 2015 Pearson Education, Inc., Upper Saddle River,
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
1 Java Object Model Part 1. 2 Type Definition: set of values – a set of values and set of operations –a set of operations that can be applied to those.
1 Java Reflection. 2 Java looking at Java l One of the unusual capabilities of Java is that a program can examine itself »You can determine the class.
1 Chapter 7 Inheritance, Polymorphism, and Scope.
Advanced Java Class Serialization. Serialization – what and why? What? –Translating the contents of an Object to a series of bytes that represent it,
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L08 (Chapter 18) Binary I/O.
13-Jul-15 Reflection. 2 Java looking at Java One of the unusual capabilities of Java is that a program can examine itself You can determine the class.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Advanced Java Programming Lecture 5 Reflection dr hab. Szymon Grabowski dr inż. Wojciech Bieniecki
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
SEG4110 – Advanced Software Design and Reengineering TOPIC H Java Reflection.
Java Reflection. Compile-Time vs Run-Time Some data you know at compile time: int area = radius*radius*3.14; The “3.14” is set – known at compile time.
Object Oriented Programming in Java Lecture 13. Java Reflection Reflection is a feature unique to Java that allows an executing program to examine or.
The Reflection Lucielle Mendez Antonio Bologna.
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.
Chap. 1 Classes, Types, and Objects. How Classes Are Declared [ ] class [extends ] [implements,, … ] { // class methods and instance variable definitions.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Object Persistence and Object serialization CSNB534 Asma Shakil.
Reflection in Java Bibliografie: Sun: The Java Tutorials – The Reflection API Java programming.
Java Programming: Advanced Topics 1 Input/Output and Serialization Chapter 3.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 10 - Interfaces.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
© Keren Kalif Advanced Java Topics Written by Keren Kalif, Edited by Liron Blecher.
1 Generics Chapter 21 Liang, Introduction to Java Programming.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
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.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
©SoftMoore ConsultingSlide 1 Serialization. ©SoftMoore ConsultingSlide 2 Serialization Allows objects to be written to a stream Can be used for persistence.
C OMP 401 R EFLECTION AND A CTION O BJECTS Instructor: Prasun Dewan.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
COSC 1P02 Data Structures and Abstraction 2.1 Cosc 1P02 Binary Files & Persistent Objects “For myself, I am an optimist--it does not seem to be much use.
CSCE 314 Programming Languages Reflection Dr. Hyunyoung Lee 1.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 12 GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology/ George Koutsogiannakis 1.
CS 151: Object-Oriented Design November 12 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Spring 2008 Mark Fontenot CSE Honors Principles of Computer Science I Note Set 20.
CSE 331 Reflection slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
03G-1 Reflection In Java “Reflection is the ability of a program to manipulate as data something representing the state of the program during its own execution.”
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
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.
Reflection Mehdi Einali Advanced Programming in Java 1.
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
The AP Java Subset Topics. A Topics Primitive Types int double boolean.
OBJECT ORIENTED PROGRAMMING II LECTURE 21 GEORGE KOUTSOGIANNAKIS
Chapter 7: Cloning and RTTI
NESTED CLASSES REFLECTION PROXIES.
CSE 413, Autumn 2002 Programming Languages
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
CSCE 314: Programming Languages Dr. Dylan Shell
Reflection in Java By: Zachary Cava.
Presentation transcript:

1 Java object model Part 3: Serialization & Reflection

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 reflection classesJava API includes several reflection classes, 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 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!}); }

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;