0% found this document useful (0 votes)
3 views9 pages

Chapter 6

The document discusses object cloning and proxies in Java, explaining the difference between copying and cloning, as well as the concepts of shallow and deep copies. It provides examples of both shallow and deep copy implementations using the Project and WrittenBy classes, highlighting how changes to original objects affect their clones. Additionally, the document details the creation and properties of dynamic proxy classes, including restrictions and methods related to proxy class generation.

Uploaded by

zohosaravanan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views9 pages

Chapter 6

The document discusses object cloning and proxies in Java, explaining the difference between copying and cloning, as well as the concepts of shallow and deep copies. It provides examples of both shallow and deep copy implementations using the Project and WrittenBy classes, highlighting how changes to original objects affect their clones. Additionally, the document details the creation and properties of dynamic proxy classes, including restrictions and methods related to proxy class generation.

Uploaded by

zohosaravanan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Object Cloning and Proxies 6.

6 Object Cloning and Proxies


6.1 Object Cloning
Copying
When you make a copy of a variable, the original and the copy are references to
the same object. This means a change to either variable also affects the other.

Employee original = new Employee("John Public", 50000);


Employee copy = original;
copy.raiseSalary(10); // oops--also changed original

Copy

original =
Employee

copy =

Figure 6.1 Copying


Cloning
If you would like copy to be a new object that begins its life being identical to
original but whose state can diverge over time, then you use the clone method.
Employee copy = original.clone();
copy.raiseSalary(10); // OK--original unchanged

Cloning

original =
Employee

copy =
Employee

Figure 6.2 Cloning


6.2 Java Programming Paradigms

Types of Cloning
Two types of copying an object
1. Shallow copy
2. Deep copy
Shallow Copy
Shallow copy is a bit-wise copy of an object. A new object is created that has an
exact copy of the values in the original object. If any of the fields of the object are
references to other objects, just the reference addresses are copied i.e., only the memory
address is copied.

Figure 6.3 Shallow Copy


In this figure 6.3 , the MainObject1 have fields "field1" of int type, and
"ContainObject1" of ContainObject type. When you do a shallow copy of MainObject1,
MainObject2 is created with "field3" containing the copied value of "field1" and still
pointing to ContainObject1 itself. Observe here and you will find that since field1 is of
primitive type, the values of it are copied to field3 but ContainedObject1 is an object, so
MainObject2 is still pointing to ContainObject1. So any changes made to ContainObject1
in MainObject1 will reflect in MainObject2.
Deep Copy
A deep copy copies all fields, and makes copies of dynamically allocated memory
pointed to by the fields. A deep copy occurs when an object is copied along with the
objects to which it refers.

Figure 6.4 Deep Copy


Object Cloning and Proxies 6.3

In this figure 6.4, the MainObject1 have fields "field1" of int type, and
"ContainObject1" of ContainObject type. When you do a deep copy of MainObject1,
MainObject2 is created with "field3" containing the copied value of "field1" and
"ContainObject2" containing the copied value of ContainObject1.So any changes made
to ContainObject1 in MainObject1 will not reflect in MainObject2.

Shallow copy
class WrittenBy
{
private String name;
public String getName()
{
return name;
}
public void setName(String s)
{
name = s;
}
public WrittenBy(String s)
{
name = s;
}
}
class Project implements Cloneable
{
//Contained object
private WrittenBy write;
private String name;
public WrittenBy getWrite()
{
return write;
}
public String getName()
{
return name;
}
public void setName(String s)
{
name = s;
}
public Project(String s, String pro)
{
6.4 Java Programming Paradigms

name = s;
write = new WrittenBy(pro);
}
public Object clone()
{
//shallow copy
try
{
return super.clone();
}
catch (CloneNotSupportedException e)
{
return null;
}
}
}
public class ShallowCopy
{
public static void main(String[] args)
{
//Original Object
Project write = new Project("OAK","james");
System.out.println("Original Object: " + write.getName() + " - "+ write.getWrite().getName());
//Clone Object
Project clonedproj = (Project) write.clone();
System.out.println("Cloned Object:" + clonedproj.getName() + " - "+
clonedproj.getWrite().getName());

write.setName("Java");
write.getWrite().setName("James Gosling");

System.out.println("Original Object after it is updated: " + write.getName() + " - " +


write.getWrite().getName());

System.out.println("Cloned Object after updating original object: "+ clonedproj.getName()


+ " - " + clonedproj.getWrite().getName());
}
}
Program 6.1 Shallow copying
Output
I:\java\OOPS>javac ShallowCopy.java
I:\java\OOPS>java ShallowCopy
Object Cloning and Proxies 6.5

Original Object: OAK - james


Cloned Object: OAK - james
Original Object after it is updated: Java - James Gosling
Cloned Object after updating original object: OAK - James Gosling

From the above example, implement the class that you want to copy with
Clonable interface and override clone() method of Object class and call super.clone() in
it. If you observe, the changes made to "name" field of original object (Project class) is
not reflected in cloned object but the changes made to "name" field of contained object
(WrittenBy class) is reflected in cloned object. This is because the cloned object carries
the memory address of the WrittenBy object but not the actual values. Hence any updates
on the WrittenBy object in Original object will reflect in Cloned object.

Deep copy
class WrittenBy
{
private String name;
public String getName()
{
return name;
}
public void setName(String s)
{
name = s;
}
public WrittenBy(String s)
{
name = s;
}
}
class Project implements Cloneable
{
//Contained object
private WrittenBy write;
private String name;
public WrittenBy getWrite()
{
return write;
}
public String getName()
{
return name;
6.6 Java Programming Paradigms

}
public void setName(String s)
{
name = s;
}
public Project(String s, String pro)
{
name = s;
write = new WrittenBy(pro);
}
public Object clone()
{
//Deep Copy
Project p=new Project(name, write.getName());
return p;
}
}
public class DeepCopy
{
public static void main(String[] args)
{
//Original Object
Project write = new Project("OAK","james");
System.out.println("Original Object: " + write.getName() + " - "+
write.getWrite().getName());
//Clone Object
Project clonedproj = (Project) write.clone();
System.out.println("Cloned Object:" + clonedproj.getName() + " -
"+clonedproj.getWrite().getName());

write.setName("Java");
write.getWrite().setName("James Gosling");

System.out.println("Original Object after it is updated: " + write.getName() + " - "


+ write.getWrite().getName());

System.out.println("Cloned Object after updating original object: "+


clonedproj.getName() + " - " + clonedproj.getWrite().getName());
}
}
Program 6.2 Example for DeepCopy
Object Cloning and Proxies 6.7

Output
I:\java\OOPS>javac DeepCopy.java

I:\java\OOPS>java DeepCopy
Original Object: OAK - james
Cloned Object:OAK - james
Original Object after it is updated: Java - James Gosling
Cloned Object after updating original object: OAK - james

Notice that in the "Project" class, you will see only the change in the "clone()" method.
Since its a deep copy, you need to create an object of the cloned class.

6.2 Proxy Class


A dynamic proxy class is a class that implements a list of interfaces specified at
runtime such that a method invocation through one of the interfaces on an instance of the
class will be encoded and dispatched to another object through a uniform interface. Thus,
a dynamic proxy class can be used to create a type-safe proxy object for a list of
interfaces without requiring pre-generation of the proxy class, such as with compile-time
tools. Method invocations on an instance of a dynamic proxy class are dispatched to a
single method in the instance's invocation handler, and they are encoded with a
java.lang.reflect.Method object identifying the method that was invoked and an array of
type Object containing the arguments.

Dynamic Proxy Class API


 A dynamic proxy class (simply referred to as a proxy class below) is a class that
implements a list of interfaces specified at runtime when the class is created.
 A proxy interface is such an interface that is implemented by a proxy class.
 A proxy instance is an instance of a proxy class.

6.2.1 Creating a Proxy Class


Proxy classes, as well as instances of them, are created using the static methods of
the class java.lang.reflect.Proxy.

The Proxy.getProxyClass method returns the java.lang.Class object for a


proxy class given a class loader and an array of interfaces. The proxy class will be
defined in the specified class loader and will implement all of the supplied interfaces. If a
proxy class for the same permutation of interfaces has already been defined in the class
loader, then the existing proxy class will be returned; otherwise, a proxy class for those
interfaces will be generated dynamically and defined in the class loader.
6.8 Java Programming Paradigms

There are several restrictions on the parameters that may be passed to


Proxy.getProxyClass:

 All of the Class objects in the interfaces array must represent interfaces, not
classes or primitive types.
 No two elements in the interfaces array may refer to identical Class objects.
 All of the interface types must be visible by name through the specified class loader.
In other words, for class loader cl and every interface i, the following expression
must be true:
 Class.forName(i.getName(), false, cl) == i
 All non-public interfaces must be in the same package; otherwise, it would not be
possible for the proxy class to implement all of the interfaces, regardless of what
package it is defined in.
 For any set of member methods of the specified interfaces that have the same
signature:
o If the return type of any of the methods is a primitive type or void, then all of
the methods must have that same return type.
o Otherwise, one of the methods must have a return type that is assignable to all
of the return types of the rest of the methods.
 The resulting proxy class must not exceed any limits imposed on classes by the
virtual machine. For example, the VM may limit the number of interfaces that a
class may implement to 65535; in that case, the size of the interfaces array
must not exceed 65535.

If any of these restrictions are violated, Proxy.getProxyClass will throw an


IllegalArgumentException. If the interfaces array argument or any of its elements
are null, a NullPointerException will be thrown.

6.2.2 Proxy Class Properties


A proxy class has the following properties:
 Proxy classes are public, final, and not abstract.
 The unqualified name of a proxy class is unspecified. The space of class names
that begin with the string "$Proxy" is, however, to be reserved for proxy classes.
 A proxy class extends java.lang.reflect.Proxy.
 A proxy class implements exactly the interfaces specified at its creation, in the
same order.
 If a proxy class implements a non-public interface, then it will be defined in the
same package as that interface. Otherwise, the package of a proxy class is also
unspecified. Note that package sealing will not prevent a proxy class from being
successfully defined in a particular package at runtime, and neither will classes
Object Cloning and Proxies 6.9

already defined in the same class loader and the same package with particular
signers.
 Since a proxy class implements all of the interfaces specified at its creation,
invoking getInterfaces on its Class object will return an array containing the same
list of interfaces (in the order specified at its creation), invoking getMethods on its
Class object will return an array of Method objects that include all of the methods
in those interfaces, and invoking getMethod will find methods in the proxy
interfaces as would be expected.
 The Proxy.isProxyClass method will return true if it is passed a proxy class-- a
class returned by Proxy.getProxyClass or the class of an object returned by
Proxy.newProxyInstance-- and false otherwise.
 The java.security.ProtectionDomain of a proxy class is the same as that of system
classes loaded by the bootstrap class loader, such as java.lang.Object, because the
code for a proxy class is generated by trusted system code. This protection
domain will typically be granted java.security.AllPermission.

Review Questions
Part-A
1) Differentiate between copying and cloning.
2) What is shallow copy?
3) What is deep copy?
4) Define proxies.
5) What are the properties of proxies classes.

Part- B
1) Describe cloning in details.
2) Describe shallow copy and deep copy with example program.
3) Describe proxy classes.

You might also like