tag:blogger.com,1999:blog-38327718378775020092024-03-18T18:20:24.655+05:30Programming MitraA friend to Java Programming Language and its related FrameworksNaresh Joshihttp://www.blogger.com/profile/01073925481525463593noreply@blogger.comBlogger40125tag:blogger.com,1999:blog-3832771837877502009.post-89863134307473908142019-08-30T15:52:00.000+05:302019-08-30T15:57:53.933+05:30Java Serialization Magic Methods And Their Uses With Example<div dir="ltr" style="text-align: left;" trbidi="on">
In a previous article <a target="_blank" href="https://www.programmingmitra.com/2019/08/what-is-serialization-everything-about-java-serialization-explained-with-example.html">Everything You Need to Know About Java Serialization</a>, we discussed how serializability of a class is enabled by implementing the <code>Serializable</code> interface. If our class does not implement <code>Serializable</code> interface or if it is having a reference to a non <code>Serializable</code> class then JVM will throw <code>NotSerializableException</code>.<br />
<br />
All subtypes of a serializable class are themselves serializable and <code>Externalizable</code> interface also extends Serializable. So even if we <a target="_blank" href="https://www.programmingmitra.com/2019/08/how-to-customize-serialization-in-java-by-using-externalizable-interface.html">customize our serialization process using Externalizable</a> our class is still a <code>Serializable</code>.<br />
<br />
The <code>Serializable</code> interface is a marker interface which has no methods or fields and it works like a flag for the JVM. The Java serialization process provided by <code>ObjectInputStream</code> and <code>ObjectOutputStream</code> classes are fully controlled by the JVM.<br />
<br />
But what if we want to add some additional logic to enhance this normal process, for example, we may want to encrypt/decrypt our sensitive information before serializing/deserializing it. Java provides us with some additional methods for this purpose which we are going to discuss in this blog.<br />
<br />
<br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhppG03AvnHAiMxvdHF8WMWr1nzUnJX0wcLqbV-0ykE9vT82Zoi44SzeWRzwua7LYMNoDXf7pcXxulNABL1_GpTg4CR2kX7QqBWrvYfKo206cK6ctDsyt7F5-ZqkzRFmpDO-UvsF9frkE0/s1600/Java-Serialization-Magic-Methods-And-Their-Uses.png" imageanchor="1"><img alt="Java-Serialization-Magic-Methods-And-Their-Uses" border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhppG03AvnHAiMxvdHF8WMWr1nzUnJX0wcLqbV-0ykE9vT82Zoi44SzeWRzwua7LYMNoDXf7pcXxulNABL1_GpTg4CR2kX7QqBWrvYfKo206cK6ctDsyt7F5-ZqkzRFmpDO-UvsF9frkE0/s1600/Java-Serialization-Magic-Methods-And-Their-Uses.png" title="Java-Serialization-Magic-Methods-And-Their-Uses" /></a><br />
<br />
<h2>
writeObject and readObject methods</h2>
Serializable classes that want to customize or add some additional logic to enhance the normal serialization/deserialization process should provide <code>writeObject</code> and <code>readObject</code> methods with these exact signatures:<br />
<ul>
<li><code>private void writeObject(java.io.ObjectOutputStream out) throws IOException</code></li>
<li><code>private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException</code></li>
</ul>
These methods are already discussed in great details under article <a target="_blank" href="https://www.programmingmitra.com/2019/08/what-is-serialization-everything-about-java-serialization-explained-with-example.html">Everything You Need to Know About Java Serialization</a>.<br />
<br />
<h2>
readObjectNoData method</h2>
As described in Java docs of <code>Serializable</code> class, if we want to initialize the state of the object for its particular class in the event that the serialization stream does not list the given class as a superclass of the object being deserialized then we should provide <code>writeObject</code> and <code>readObject</code> methods with these exact signatures:<br />
<ul>
<li><code>private void readObjectNoData() throws ObjectStreamException</code></li>
</ul>
This may occur in cases where the receiving party uses a different version of the deserialized instance's class than the sending party, and the receiver's version extends classes that are not extended by the sender's version. This may also occur if the serialization stream has tampered; hence, readObjectNoData is useful for initializing deserialized objects properly despite a "hostile" or incomplete source stream.<br />
<br />
Each serializable class may define its own <code>readObjectNoData</code> method. If a serializable class does not define a <code>readObjectNoData</code> method, then in the circumstances listed above the fields of the class will be initialized to their default values.<br />
<br />
<h2>
writeReplace and readResolve methods</h2>
Serializable classes that need to designate an alternative object to be used when writing an object to the stream should provide this special method with the exact signature:<br />
<ul>
<li><code>ANY-ACCESS-MODIFIER Object writeReplace() throws ObjectStreamException</code></li>
</ul>
And Serializable classes that need to designate a replacement when an instance of it is read from the stream should provide this special method with the exact signature:<br />
<ul>
<li><code>ANY-ACCESS-MODIFIER Object readResolve() throws ObjectStreamException</code></li>
</ul>
Basically, the <code>writeReplace</code> method allows the developer to provide a replacement object that will be serialized instead of the original one. And the <code>readResolve</code> method is used during deserialization process to replace the de-serialized object by another one of our choices.<br />
<br />
One of the main usages of writeReplace and readResolve methods is to implement the singleton design pattern with Serialized classes. We know that the <a target="_blank" href="https://www.programmingmitra.com/2016/05/different-ways-to-create-objects-in-java-with-example.html">deserialization process creates a new object every time</a> and it can also be <a target="_blank" href="https://www.programmingmitra.com/2019/08/how-to-deep-clone-an-object-using-java-in-memory-serialization.html">used as a method to deeply clone an object</a>, which is not good if we have to make our class singleton.<br />
<br />
<blockquote>
You can read more about Java cloning and serialization on <a target="_blank" href="https://www.programmingmitra.com/search/label/Java%20Cloning">Java Cloning</a> and <a target="_blank" href="https://www.programmingmitra.com/search/label/Serialization">Java Serialization</a> topics.</blockquote>
<br />
The method <code>readResolve</code> is called after <code>readObject</code> has returned (conversely <code>writeReplace</code> is called before <code>writeObject</code> and probably on a different object). The object the method returns replaces <code>this</code> object returned to the user of <code>ObjectInputStream.readObject</code> and any further back-references to the object in the stream. We can use the writeReplace method to replace serializing object with null so nothing will be serialized and then use the readResolve method to replace the deserialized object with the singleton instance.<br />
<br />
<h2>
validateObject method</h2>
If we want to perform certain validations on some of our fields we can do that by implementing <code>ObjectInputValidation</code> interface and overriding <code>validateObject</code> method from it.<br />
<br />
Method <code>validateObject</code> will automatically get called when we register this validation by calling <code>ObjectInputStream.registerValidation(this, 0)</code> from <code>readObject</code> method. It is very useful to verify the stream has not been tampered with, or that the data makes sense before handing it back to your application.<br />
<br />
Below example covers code for all above methods<br />
<br />
<pre><code class="language-java" lang="java">public class SerializationMethodsExample {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Employee emp = new Employee("Naresh Joshi", 25);
System.out.println("Object before serialization: " + emp.toString());
// Serialization
serialize(emp);
// Deserialization
Employee deserialisedEmp = deserialize();
System.out.println("Object after deserialization: " + deserialisedEmp.toString());
System.out.println();
// This will print false because both object are separate
System.out.println(emp == deserialisedEmp);
System.out.println();
// This will print false because both `deserialisedEmp` and `emp` are pointing to same object,
// Because we replaced de-serializing object in readResolve method by current instance
System.out.println(Objects.equals(emp, deserialisedEmp));
}
// Serialization code
static void serialize(Employee empObj) throws IOException {
try (FileOutputStream fos = new FileOutputStream("data.obj");
ObjectOutputStream oos = new ObjectOutputStream(fos))
{
oos.writeObject(empObj);
}
}
// Deserialization code
static Employee deserialize() throws IOException, ClassNotFoundException {
try (FileInputStream fis = new FileInputStream("data.obj");
ObjectInputStream ois = new ObjectInputStream(fis))
{
return (Employee) ois.readObject();
}
}
}
class Employee implements Serializable, ObjectInputValidation {
private static final long serialVersionUID = 2L;
private String name;
private int age;
public Employee(String name, int age) {
this.name = name;
this.age = age;
}
// With ObjectInputValidation interface we get a validateObject method where we can do our validations.
@Override
public void validateObject() {
System.out.println("Validating age.");
if (age < 18 || age > 70)
{
throw new IllegalArgumentException("Not a valid age to create an employee");
}
}
// Custom serialization logic,
// This will allow us to have additional serialization logic on top of the default one e.g. encrypting object before serialization.
private void writeObject(ObjectOutputStream oos) throws IOException {
System.out.println("Custom serialization logic invoked.");
oos.defaultWriteObject(); // Calling the default serialization logic
}
// Replacing de-serializing object with this,
private Object writeReplace() throws ObjectStreamException {
System.out.println("Replacing serialising object by this.");
return this;
}
// Custom deserialization logic
// This will allow us to have additional deserialization logic on top of the default one e.g. performing validations, decrypting object after deserialization.
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
System.out.println("Custom deserialization logic invoked.");
ois.registerValidation(this, 0); // Registering validations, So our validateObject method can be called.
ois.defaultReadObject(); // Calling the default deserialization logic.
}
// Replacing de-serializing object with this,
// It will will not give us a full proof singleton but it will stop new object creation by deserialization.
private Object readResolve() throws ObjectStreamException {
System.out.println("Replacing de-serializing object by this.");
return this;
}
@Override
public String toString() {
return String.format("Employee {name='%s', age='%s'}", name, age);
}
}
</code></pre>
<br />
You can find the complete source code for this article on this <a target="_blank" href="https://github.com/njnareshjoshi/exercises/blob/master/src/org/programming/mitra/exercises/SerializationMethodsExample.java">Github Repository</a> and please feel free to provide your valuable feedback.</div>
Naresh Joshihttp://www.blogger.com/profile/01073925481525463593noreply@blogger.com0tag:blogger.com,1999:blog-3832771837877502009.post-30055085102425937622019-08-18T12:58:00.000+05:302019-08-30T16:38:12.402+05:30How To Deep Clone An Object Using Java In Memory Serialization<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
In my previous articles, I had explained the <a href="https://www.programmingmitra.com/2016/11/Java-Cloning-Types-of-Cloning-Shallow-Deep-in-Details-with-Example.html" target="_blank">difference between deep and shallow cloning</a> and <a href="https://www.programmingmitra.com/2017/01/Java-cloning-copy-constructor-versus-Object-clone-or-cloning.html" target="_blank">how copy-constructors</a> and <a href="https://www.programmingmitra.com/2017/01/java-cloning-why-copy-constructors-are-not-sufficient-or-good.html" target="_blank">defensive copy methods</a> are better than default java cloning.<br />
<br />
<a href="https://www.programmingmitra.com/2016/11/Java-Cloning-Types-of-Cloning-Shallow-Deep-in-Details-with-Example.html" target="_blank">Java object cloning</a> using <a href="https://www.programmingmitra.com/2017/01/Java-cloning-copy-constructor-versus-Object-clone-or-cloning.html" target="_blank">copy constructors</a> and <a href="https://www.programmingmitra.com/2017/01/java-cloning-why-copy-constructors-are-not-sufficient-or-good.html" target="_blank">defensive copy methods</a> certainly have some advantages but we have to explicitly write some code to achieve deep cloning in all these approaches. And still, there are chances that we might miss something and do not get deeply cloned object.<br />
<br />
And as discussed in <a href="https://www.programmingmitra.com/2016/05/different-ways-to-create-objects-in-java-with-example.html" target="_blank">5 different ways to create objects in java</a>, deserialising a serialised object creates a new object with the same state as in the serialized object. So similar to above cloning approaches we can achieve deep cloning functionality using object <a href="https://www.programmingmitra.com/2019/08/what-is-serialization-everything-about-java-serialization-explained-with-example.html" target="_blank">serialization and deserialization</a> as well and with this approach we do not have worry about or write code for deep cloning, we get it by default.<br />
<br />
However, cloning an object using serialization comes with some performance overhead and we can improve on it by using <strong>in-memory serialization</strong> if we just need to clone the object and don’t need to persist it in a file for future use.<br />
<br />
We will use below <code>Employee</code> class as an example which has <code>name</code>, <code>doj</code> and <code>skills</code> as the state, for deep cloning, we do not need to worry about the name field because it is a String object and by default all <a href="https://www.programmingmitra.com/2018/02/why-string-is-immutable-and-final-in-java.html" target="_blank">strings are immutable in nature</a>.</div>
<br />
<blockquote>
You can read more about immutability on <a href="https://www.programmingmitra.com/2018/02/how-to-create-immutable-class-in-java.html" target="_blank">How to Create an Immutable Class in Java </a>and <a href="https://www.programmingmitra.com/2018/02/why-string-is-immutable-and-final-in-java.html" target="_blank">Why String is Immutable and Final</a>.</blockquote>
<br />
<pre><code class="language-java" lang="java">class Employee implements Serializable {
private static final long serialVersionUID = 2L;
private String name;
private LocalDate doj;
private List<String> skills;
public Employee(String name, LocalDate doj, List<String> skills) {
this.name = name;
this.doj = doj;
this.skills = skills;
}
public String getName() { return name; }
public LocalDate getDoj() { return doj; }
public List<String> getSkills() { return skills; }
// Method to deep clone a object using in memory serialization
public Employee deepClone() throws IOException, ClassNotFoundException {
// First serializing the object and its state to memory using ByteArrayOutputStream instead of FileOutputStream.
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos);
out.writeObject(this);
// And then deserializing it from memory using ByteArrayOutputStream instead of FileInputStream.
// Deserialization process will create a new object with the same state as in the serialized object,
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream in = new ObjectInputStream(bis);
return (Employee) in.readObject();
}
@Override
public String toString() {
return String.format("Employee{name='%s', doj=%s, skills=%s}", name, doj, skills);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Employee employee = (Employee) o;
return Objects.equals(name, employee.name) &&
Objects.equals(doj, employee.doj) &&
Objects.equals(skills, employee.skills);
}
@Override
public int hashCode() {
return Objects.hash(name, doj, skills);
}
}
</code></pre>
<br />
<br />
To deep clone an object of <code>Employee</code> class, I have provided a <code>deepClone()</code> method which serializes the object to memory by using <code>ByteArrayOutputStream</code> instead of the <code>FileOutputStream</code> and deserialises it back using <code>ByteArrayInputStream</code> instead of the <code>FileInputStream</code>. Here we are serializing the object into bytes and deserializing it from bytes to object again.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiRUju0iQqlzqxFfv5tVp-yikHcgt5FaVk9PsdzQBPd40j9teKFDjJc7MkBdrLpB1IK5KjCFQmjtQCsvT4thSun21LvU8o5_dyLDpXo-Epexf6NHd9J9yFB_wpQQpbA_F8zY5pZCrToUqg/s1600/Java-Deep-Cloning-Using-Serialization.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img alt="How To Deep Clone An Object Using Java In Memory Serialization" border="0" data-original-height="390" data-original-width="1600" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiRUju0iQqlzqxFfv5tVp-yikHcgt5FaVk9PsdzQBPd40j9teKFDjJc7MkBdrLpB1IK5KjCFQmjtQCsvT4thSun21LvU8o5_dyLDpXo-Epexf6NHd9J9yFB_wpQQpbA_F8zY5pZCrToUqg/s1600/Java-Deep-Cloning-Using-Serialization.png" title="How To Deep Clone An Object Using Java In Memory Serialization" /></a></div>
<br />
<br />
<br />
Employee class implements <code>Serializable</code> interface to achieve serialization which has its own disadvantages and we can overcome some of these disadvantages by <a href="https://www.programmingmitra.com/2019/08/how-to-customize-serialization-in-java-by-using-externalizable-interface.html" target="_blank">customizing the serialization process by using Externalizable interface</a>.<br />
<br />
We can run below tests to see if our cloning approach is deep or just shallow, here all <code>==</code> operations will return false (because both objects are separate) and all <code>equals</code> will return true (because both have the same content).<br />
<br />
<pre><code class="language-java" lang="java">public static void main(String[] args) throws IOException, ClassNotFoundException {
Employee emp = new Employee("Naresh Joshi", LocalDate.now(), Arrays.asList("Java", "Scala", "Spring"));
System.out.println("Employee object: " + emp);
// Deep cloning `emp` object by using our `deepClone` method.
Employee clonedEmp = emp.deepClone();
System.out.println("Cloned employee object: " + clonedEmp);
System.out.println();
// All of this will print false because both objects are separate.
System.out.println(emp == clonedEmp);
System.out.println(emp.getDoj() == clonedEmp.getDoj());
System.out.println(emp.getSkills() == clonedEmp.getSkills());
System.out.println();
// All of this will print true because `clonedEmp` is a deep clone of `emp` and both have the same content.
System.out.println(Objects.equals(emp, clonedEmp));
System.out.println(Objects.equals(emp.getDoj(), clonedEmp.getDoj()));
System.out.println(Objects.equals(emp.getSkills(), clonedEmp.getSkills()));
}
</code></pre>
<br />
We know the deserialization process creates a new object every time which is not good if we have to make our class singleton. And that's why we need to override and disable serialization for our singleton class which we can achieve by providing writeReplace and readResolve methods.<br />
<br />
Similar to serialization, Java cloning also does not play along with singleton pattern, and that's why we need to override and disable it as well. We can do that by implementing cloning in a way so that it will either throw <code>CloneNotSupportedException</code> or return the same instance every time.<br />
<br />
<blockquote>
You can read more about Java cloning and serialization on <a href="https://www.programmingmitra.com/search/label/Java%20Cloning" target="_blank">Java Cloning</a> and <a href="https://www.programmingmitra.com/search/label/Serialization" target="_blank">Java Serialization</a> topics.</blockquote>
<br />
You can find the complete source code for this article on this <a href="https://github.com/njnareshjoshi/exercises/blob/master/src/org/programming/mitra/exercises/DeepCloningUsingSerializationExample.java" target="_blank">Github Repository</a> and please feel free to provide your valuable feedback.
</div>
Naresh Joshihttp://www.blogger.com/profile/01073925481525463593noreply@blogger.com1tag:blogger.com,1999:blog-3832771837877502009.post-29238184516634713412019-08-11T19:20:00.000+05:302019-08-30T18:00:27.694+05:30How to Customize Serialization In Java By Using Externalizable Interface<div dir="ltr" style="text-align: left;" trbidi="on">
In a previous article <a href="https://www.programmingmitra.com/2019/08/what-is-serialization-everything-about-java-serialization-explained-with-example.html">Everything About Java Serialization Explained With Example</a>, I explained how we can serialize/deserialize one object using <code>Serializable</code> interface and also explain how we can <a href="https://www.programmingmitra.com/2019/08/java-serialization-magic-methods-and-their-uses-with-example.html" target="_blank">customise the serialization process using writeObject and readObject methods</a>.<br />
<br />
<h2>
Disadvantages Of Java Serialization Process</h2>
But these customizations are not sufficient because JVM has full control of the serialization process and those customization logics are just additions to the default serialization process. We still have to use the default serialization logic by calling <code>ObjectOutputStream.defaultWriteObject()</code> and <code>ObjectInputStream.defaultReadObject()</code> from <code>writeObject</code> and <code>readObject</code> methods. And if do not call these default methods our object will not be serialized/deserialized.<br />
<br />
The default serialization process is fully recursive. So whenever we try to serialize one object, the serialization process try to serialize all the fields (primitive and reference) with our class (except <code>static</code> and <code>transient</code> fields). Which makes serialization a very slow process.<br />
<br />
Now let's assume we have an object with lots of fields which we do not want to serialize for some reasons (these fields will always be assigned with default values). With default serialization process we will have to make all these fields transient but it still will not be efficient because there will be a lot of checks to see if the fields are transient or not.<br />
<br />
So as we can see there are lots of downside of the using default serialization process, like:<br />
<ol>
<li>Customizations to serialization are not sufficient because JVM has full control of the serialization process and our customization logics are just additions to the default serialization process.</li>
<li>Default serialization process is fully recursive and slow.</li>
<li>In order to not to serialize a field, we have to declare it transient and lots of transient fields will again make the process slow.</li>
<li>We can not control how our fields will be serialized and deserialized.</li>
<li>Default serialization process does not invoke constructors while creating the object so it can not call the initialization logic provided by the constructor.</li>
</ol>
<br />
<h2>
What Is Externalization And Externalizable Interface</h2>
<br />
As we saw above that the default java serialization is not efficient. We can solve some of these issues by using <code>Externalizable</code> interface instead of <code>Serializable</code> interface.<br />
<br />
We can write your own serialization logic by implementing the <a href="https://docs.oracle.com/javase/7/docs/api/java/io/Externalizable.html">Externalizable</a> interface and overriding it’s methods <code>writeExternal()</code> and <code>readExternal()</code>. But with this approach, we will not get any kind of default serialization logic from JVM and it is up to us to provide the complete serialization and deserialization logic.<br />
<br />
So it is very necessary to code the test these methods very carefully because it might break the serialization process. But the externalization process is very fast in comparison to the default serialization process if implemented properly.<br />
<br />
We will use below <code>Employee</code> class object as an example for the explanation:<br />
<br />
<pre><code class="language-java" lang="java">// Using Externalizable, complete serialization/deserialization logic becomes our responsibility,
// We need to tell what to serialize using writeExternal() method and what to deserialize using readExternal(),
// We can even serialize/deserialize static and transient variables,
// With implementation of writeExternal() and readExternal(), methods writeObject() and readObject() becomes redundant and they do not get called.
class Employee implements Externalizable {
// This serialVersionUID field is necessary for Serializable as well as Externalizable to provide version control,
// Compiler will provide this field if we do not provide it which might change if we modify class structure of our class, and we will get InvalidClassException,
// If we provide a value to this field and do not change it, serialization-deserialization will not fail if we change our class structure.
private static final long serialVersionUID = 2L;
private String firstName;
private transient String lastName; // Using Externalizable, we can even serialize/deserialize transient variables, so declaring fields transient becomes unnecessary.
private int age;
private static String department; // Using Externalizable, we can even serialize/deserialize static variables according to our need.
// Mandatory to have to make our class Externalizable
// When an Externalizable object is reconstructed, the object is created using public no-arg constructor before the readExternal method is called.
// If a public no-arg constructor is not present then a InvalidClassException is thrown at runtime.
public Employee() {
}
// All-arg constructor to create objects manually
public Employee(String firstName, String lastName, int age, String department) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
Employee.department = department;
validateAge();
}
private void validateAge() {
System.out.println("Validating age.");
if (age < 18 || age > 70) {
throw new IllegalArgumentException("Not a valid age to create an employee");
}
}
@Override
// We need to tell what to serialize in writeExternal() method
public void writeExternal(ObjectOutput out) throws IOException {
System.out.println("Custom externalizable serialization logic invoked.");
out.writeUTF(firstName);
out.writeUTF(lastName);
out.writeInt(age);
out.writeUTF(department);
}
@Override
// We need to tell what to deserialize in readExternal() method
// The readExternal method must read the values in the same sequence and with the same types as were written by writeExternal
public void readExternal(ObjectInput in) throws IOException {
System.out.println("Custom externalizable serialization logic invoked.");
firstName = in.readUTF();
lastName = in.readUTF();
age = in.readInt();
department = in.readUTF();
validateAge();
}
@Override
public String toString() {
return String.format("Employee {firstName='%s', lastName='%s', age='%s', department='%s'}", firstName, lastName, age, department);
}
// Custom serialization logic, It will be called only if we have implemented Serializable instead of Externalizable.
private void writeObject(ObjectOutputStream oos) throws IOException {
System.out.println("Custom serialization logic invoked.");
}
// Custom deserialization logic, It will be called only if we have implemented Serializable instead of Externalizable.
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
System.out.println("Custom deserialization logic invoked.");
}
}
</code></pre>
<br />
<h2>
How Serialization works with Externalizable Interface</h2>
As we can see above in our example <code>Employee</code> class, we can write your own serialization logic by implementing the <a href="https://docs.oracle.com/javase/7/docs/api/java/io/Externalizable.html">Externalizable</a> interface and overriding its methods <code>writeExternal()</code> and <code>readExternal()</code>.<br />
<br />
The object can implement the writeExternal method to save its contents by calling the methods of DataOutput for its primitive values or calling the writeObject method of ObjectOutput for objects, strings, and arrays.<br />
<br />
The object can implement the readExternal method to restore its contents by calling the methods of DataInput for primitive types and readObject for objects, strings and arrays. The readExternal method must read the values in the same sequence and with the same types as were written by writeExternal.<br />
<br />
<pre><code class="language-java" lang="java">// We need to tell what fields to serialize in writeExternal() method
public void writeExternal(ObjectOutput out) throws IOException {
System.out.println("Custom externalizable serialization logic invoked.");
out.writeUTF(firstName);
out.writeUTF(lastName);
out.writeInt(age);
out.writeUTF(department);
}
// We need to tell what fields to deserialize in readExternal() method
// The readExternal method must read the values in the same sequence and with the same types as were written by writeExternal
public void readExternal(ObjectInput in) throws IOException {
System.out.println("Custom externalizable serialization logic invoked.");
firstName = in.readUTF();
lastName = in.readUTF();
age = in.readInt();
department = in.readUTF();
validateAge();
}
</code></pre>
<br />
To serialize and deserialize our object to a file we need to follow the same procedure as we followed in the Serializable example which means calling <code>ObjectOutputStream.writeObject()</code> and <code>ObjectInputStream.readObject()</code> as done in the following code:<br />
<br />
<pre><code class="language-java" lang="java">public class ExternalizableExample {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Employee empObj = new Employee("Shanti", "Sharma", 25, "IT");
System.out.println("Object before serialization => " + empObj.toString());
// Serialization
serialize(empObj);
// Deserialization
Employee deserializedEmpObj = deserialize();
System.out.println("Object after deserialization => " + deserializedEmpObj.toString());
}
// Serialization code
static void serialize(Employee empObj) throws IOException {
try (FileOutputStream fos = new FileOutputStream("data.obj");
ObjectOutputStream oos = new ObjectOutputStream(fos))
{
oos.writeObject(empObj);
}
}
// Deserialization code
static Employee deserialize() throws IOException, ClassNotFoundException {
try (FileInputStream fis = new FileInputStream("data.obj");
ObjectInputStream ois = new ObjectInputStream(fis))
{
return (Employee) ois.readObject();
}
}
}
</code></pre>
<br />
The <code>Externalizable</code> interface is a child interface of <code>Serializable</code> i.e. <code>Externalizable extends Serializable</code>. So if we implement <code>Externalizable</code> interface and override its <code>writeExternal()</code> and <code>readExternal()</code> methods then first preference is given to these methods over the default serialization mechanism provided by JVM. These methods supersede customized implementations of <code>writeObject</code> and <code>readObject</code> methods, So if we also provide <code>writeObject()</code> and <code>readObject()</code> then they will be ignored.<br />
<br />
In the serialization process, each object to be serialized is tested for the Externalizable interface. If the object supports Externalizable, the writeExternal method is called. If the object does not support Externalizable and does implement Serializable, the object is saved using ObjectOutputStream.<br />
<br />
When an Externalizable object is reconstructed, an instance is created using the public no-arg constructor, then the readExternal method called. Serializable objects are restored by reading them from an ObjectInputStream.<br />
<br />
<blockquote>
<ol>
<li>When an Externizable object is reconstructed, and object is created using public no-arg constructor before the readExternal method is called. If a public no-arg constructor is not present then a InvalidClassException is thrown at runtime.</li>
<li>Using Externalizable, we can even serialize/deserialize transient variables, so declaring fields transient becomes unnecessary.</li>
<li>Using Externalizable, we can even serialize/deserialize static variables if we need to.</li>
</ol>
</blockquote>
<br />
An Externalizable instance can designate a substitution object via the writeReplace and readResolve methods documented in the Serializable interface.<br />
<br />
Java <a href="https://www.programmingmitra.com/2019/08/how-to-deep-clone-an-object-using-java-in-memory-serialization.html">serialization can also be used to deep clone an object</a>. Java cloning is the most debatable topic in Java community and it surely does have its drawbacks but it is still the most popular and easy way of creating a copy of an object until that object is full filling mandatory conditions of Java cloning. I have covered cloning in details in a 3 article long <a href="https://programmingmitra.blogspot.in/search/label/Java%20Cloning">Java Cloning Series</a> which includes articles like <a href="https://programmingmitra.blogspot.in/2016/11/Java-Cloning-Types-of-Cloning-Shallow-Deep-in-Details-with-Example.html">Java Cloning And Types Of Cloning (Shallow And Deep) In Details With Example</a>, <a href="https://programmingmitra.blogspot.in/2017/01/Java-cloning-copy-constructor-versus-Object-clone-or-cloning.html">Java Cloning - Copy Constructor Versus Cloning</a>, <a href="https://programmingmitra.blogspot.in/2017/01/java-cloning-why-copy-constructors-are-not-sufficient-or-good.html">Java Cloning - Even Copy Constructors Are Not Sufficient</a>, go ahead and read them if you want to know more about cloning.
<br />
<br />
<h2>
Differences between Externalizable vs Serializable</h2>
Let’s list down the main differences between Externalizable and Serializable interfaces in java.<br />
<br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgVLLxwya6DsC0Cvs1HCukWBmCQ6571Cd4nPlBbseNQBYb25C-E7ZFiiaNdvGRdEUVdQg4sQTqGo2Zo7yDb6QKwvC_a1MkCUfEdN3aZLYaDGQIgl3nzkHsaXq1cUZU_FZaynrau8aoPLAA/s1600/Differences-between-Externalizable-vs-Serializable.png" imageanchor="1"><img border="0" height="294" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgVLLxwya6DsC0Cvs1HCukWBmCQ6571Cd4nPlBbseNQBYb25C-E7ZFiiaNdvGRdEUVdQg4sQTqGo2Zo7yDb6QKwvC_a1MkCUfEdN3aZLYaDGQIgl3nzkHsaXq1cUZU_FZaynrau8aoPLAA/s640/Differences-between-Externalizable-vs-Serializable.png" width="640" /></a><br />
<br />
<br />
You can find the complete source code for this article on this <a href="https://github.com/njnareshjoshi/exercises/blob/master/src/org/programming/mitra/exercises/ExternalizableExample.java">Github Repository</a> and please feel free to provide your valuable feedback.</div>
Naresh Joshihttp://www.blogger.com/profile/01073925481525463593noreply@blogger.com0tag:blogger.com,1999:blog-3832771837877502009.post-56999410161812167952019-08-10T21:24:00.001+05:302019-08-30T16:44:22.925+05:30What is Serialization? Everything You Need to Know About Java Serialization Explained With Example<div dir="ltr" style="text-align: left;" trbidi="on">
In a previous article, we looked at <a href="https://www.programmingmitra.com/2016/05/different-ways-to-create-objects-in-java-with-example.html" target="_blank">5 different ways to create objects in java</a>, I have explained how deserialising a serialised object creates a new object and in this blog, I am going to discuss Serialization and Deserialization in details.<br />
<br />
We will use below <code>Employee</code> class object as an example for the explanation<br />
<br />
<pre><code class="language-java" lang="java">// If we use Serializable interface, static and transient variables do not get serialize
class Employee implements Serializable {
// This serialVersionUID field is necessary for Serializable as well as Externalizable to provide version control,
// Compiler will provide this field if we do not provide it which might change if we modify the class structure of our class, and we will get InvalidClassException,
// If we provide value to this field and do not change it, serialization-deserialization will not fail if we change our class structure.
private static final long serialVersionUID = 2L;
private final String firstName; // Serialization process do not invoke the constructor but it can assign values to final fields
private transient String middleName; // transient variables will not be serialized, serialised object holds null
private String lastName;
private int age;
private static String department; // static variables will not be serialized, serialised object holds null
public Employee(String firstName, String middleName, String lastName, int age, String department) {
this.firstName = firstName;
this.middleName = middleName;
this.lastName = lastName;
this.age = age;
Employee.department = department;
validateAge();
}
private void validateAge() {
System.out.println("Validating age.");
if (age < 18 || age > 70) {
throw new IllegalArgumentException("Not a valid age to create an employee");
}
}
@Override
public String toString() {
return String.format("Employee {firstName='%s', middleName='%s', lastName='%s', age='%s', department='%s'}", firstName, middleName, lastName, age, department);
}
// Custom serialization logic,
// This will allow us to have additional serialization logic on top of the default one e.g. encrypting object before serialization
private void writeObject(ObjectOutputStream oos) throws IOException {
System.out.println("Custom serialization logic invoked.");
oos.defaultWriteObject(); // Calling the default serialization logic
}
// Custom deserialization logic
// This will allow us to have additional deserialization logic on top of the default one e.g. decrypting object after deserialization
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
System.out.println("Custom deserialization logic invoked.");
ois.defaultReadObject(); // Calling the default deserialization logic
// Age validation is just an example but there might some scenario where we might need to write some custom deserialization logic
validateAge();
}
}
</code></pre>
<h2>
</h2>
<h2>
What are Serialization and Deserialization</h2>
In Java, we create several objects which live and die accordingly and every object will certainly die when the JVM dies but sometimes we might want to reuse an object between several JVMs or we might want to transfer an object to another machine over the network.<br />
<br />
Well, <strong>serialization</strong> allows us to convert the state of an object into a byte stream, which then can be saved into a file on the local disk or sent over the network to any other machine. And <strong>deserialization</strong> allows us to reverse the process, which means reconverting the serialized byte stream to an object again.<br />
<br />
In simple words, object <strong>serialization</strong> is the process of saving an object's state to a sequence of bytes and <strong>deserialization</strong> is the process of reconstructing an object from those bytes. Generally, the complete process is called <strong>serialization</strong> but I think it is better to classify both as separate for more clarity.<br />
<br />
<blockquote>
The serialization process is platform independent, an object serialized on one platform can be deserialized on a different platform.</blockquote>
<br />
To serialize and deserialize our object to a file we need to call <code>ObjectOutputStream.writeObject()</code> and <code>ObjectInputStream.readObject()</code> as done in the following code:<br />
<br />
<pre><code class="language-java" lang="java">public class SerializationExample {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Employee empObj = new Employee("Shanti", "Prasad", "Sharma", 25, "IT");
System.out.println("Object before serialization => " + empObj.toString());
// Serialization
serialize(empObj);
// Deserialization
Employee deserialisedEmpObj = deserialize();
System.out.println("Object after deserialization => " + deserialisedEmpObj.toString());
}
// Serialization code
static void serialize(Employee empObj) throws IOException {
try (FileOutputStream fos = new FileOutputStream("data.obj");
ObjectOutputStream oos = new ObjectOutputStream(fos))
{
oos.writeObject(empObj);
}
}
// Deserialization code
static Employee deserialize() throws IOException, ClassNotFoundException {
try (FileInputStream fis = new FileInputStream("data.obj");
ObjectInputStream ois = new ObjectInputStream(fis))
{
return (Employee) ois.readObject();
}
}
}
</code></pre>
<br />
<h2>
Only classes which implement Serializable can be serialized</h2>
Similar to the Cloneable interface for <a href="https://www.programmingmitra.com/2016/11/Java-Cloning-Types-of-Cloning-Shallow-Deep-in-Details-with-Example.html">Java cloning</a> in serialization, we have one marker interface Serializable which works like a flag for the JVM. Any class which implements <code>Serializable</code> interface directly or through its parent can be serialised and classes which do not implement <code>Serializable</code> can not be serialized.<br />
<br />
Java’s default serialization process is fully recursive, so whenever we try to serialize one object, the serialization process try to serialize all the fields (primitive and reference) with our class (except <code>static</code> and <code>transient</code> fields).<br />
<br />
<blockquote>
When a class implements the<code>Serializable</code> interface, all its sub-classes are serializable as well. But when an object has a reference to another object, these objects must implement the <code>Serializable</code> interface separately. If our class is having even a single reference to a non <code>Serializable</code> class then JVM will throw <code>NotSerializableException</code>.</blockquote>
<h2>
</h2>
<h2>
Why Serializable is not implemented by Object?</h2>
Now a question arises if Serialization is very basic functionality and any class which do not implement <code>Serializable</code> can not be serialised, then why Serializable is not implemented by the <code>Object</code> itself?, By this way, all our objects could be serialized by default.<br />
<br />
The <code>Object</code> class does not implement <code>Serializable</code> interface because we may not want to serialize all the objects e.g. serialising a thread does not make any sense because thread running in my JVM would be using my system's memory, persisting it and trying to run it in your JVM would make no sense.<br />
<h2>
</h2>
<h2>
The transient and static fields do not get serialized</h2>
If we want to serialize one object but do not want to serialize some specific fields then we can mark those fields as <strong>transient</strong>.<br />
<br />
All the <strong>static</strong> fields belong to the class instead of the object, and the serialization process serialises the object so static fields can not be serialized.<br />
<br />
<blockquote>
<ol>
<li>Serialization does not care about access modifiers of the field such as <code>private</code>. All non transient and non static fields are considered part of an object's persistent state and are eligible for serialisation.</li>
<li>We can assign values to final fields in conscrutors only and serialization process do not invoke any constructor but still it can assign values to final fields.</li>
</ol>
</blockquote>
<h2>
</h2>
<h2>
What is serialVersionUID and Why should we declare it?</h2>
Suppose we have a class and we have serialized its object to a file on the disk, and due to some new requirements, we added/removed one field from our class. Now if we try to deserialize the already serialized object we will get <code>InvalidClassException</code>, why?<br />
<br />
We get it because by default JVM associates a version number to each serializable class to control the class versioning. It is used to verify that the serialized and deserialized objects have the same attributes and thus are compatible with deserialization. The version number is maintained in a field called <code>serialVersionUID</code>. If a serializable class doesn’t declare a <code>serialVersionUID</code> JVM will generate one automatically at run-time.<br />
<br />
If we change our class structure e.g. remove/add fields that version number also changes and according to JVM our class is not compatible with the class version of the serialized object. That's why we get the exception but if you really think about it, why should it be thrown just because I added a field? Couldn't the field just be set to its default value and then written out next time?<br />
<br />
Yes, it can be done by providing the <code>serialVersionUID</code> field manually and ensure it is always the same. It is highly recommended that each serializable class declares its <code>serialVersionUID</code> as the generated one is compiler dependent and thus may result in unexpected <em>InvalidClassExceptions.</em><br />
<em><br /></em>
<br />
<blockquote>
You can use a utility that comes with the JDK distribution called <code>serialver</code> to see what that code would be by default (it is just the hash code of the object by default).</blockquote>
<h2>
</h2>
<h2>
Customizing Serialization and Deserialization with writeObject and readObject methods</h2>
JVM has full control for serializing the object in the default serialization process but there are lots of downside of the using default serialization process, some of which are:<br />
<br />
<ol>
<li>It can not handle serialisation of fields which are not serializable.</li>
<li>Deserialization process does not invoke constructors while creating the object so it can not call the initialization logic provided by the constructor.</li>
</ol>
<br />
But we can override this the default serialization behaviour inside our Java class and provide some additional logic to enhance the normal process. This can be done by providing two methods <code>writeObject</code> and <code>readObject</code> inside the class that we want to serialize:<br />
<br />
<pre><code class="language-java" lang="java">// Custom serialization logic will allow us to have additional serialization logic on top of the default one e.g. encrypting object before serialization
private void writeObject(ObjectOutputStream oos) throws IOException {
// Any Custom logic
oos.defaultWriteObject(); // Calling the default serialization logic
// Any Custom logic
}
// Custom deserialization logic will allow us to have additional deserialization logic on top of the default one e.g. decrypting object after deserialization
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
// Any Custom logic
ois.defaultReadObject(); // Calling the default deserialization logic
// Any Custom logic
}
</code></pre>
<br />
Declaring both methods as private is necessary (public methods will not work) so rather than JVM nothing else can see them. This also proves that neither method is not inherited nor overridden or overloaded. JVM automatically checks these methods and call them during the serialization-deserialization process. JVM can call these private methods but other objects can not thus, the integrity of the class is maintained and the serialization protocol can continue to work as normal.<br />
<br />
Even though those specialized private methods are provided, the object serialization works the same way by calling <code>ObjectOutputStream.writeObject()</code> or <code>ObjectInputStream.readObject()</code>.<br />
<br />
The call to <code>ObjectOutputStream.writeObject()</code> or <code>ObjectInputStream.readObject()</code> kicks off the serialization protocol. First, the object is checked to ensure it implements <code>Serializable</code> and then it is checked to see whether either of those private methods is provided. If they are provided, the stream class is passed as the parameter to these methods, giving the code control over its usage.<br />
<br />
We can call <code>ObjectOutputStream.defaultWriteObject()</code> and <code>ObjectInputStream.defaultReadObject()</code> from these methods to gain default serialization logic. Those calls do what they sound like -- they perform the default writing and reading of the serialized object, which is important because we are not replacing the normal process, we are only adding to it.<br />
<br />
Those private methods can be used for any customization you want to make in the serialization process, e.g. encryption can be added to the output and decryption to the input (note that the bytes are written and read in cleartext with no obfuscation at all). They could be used to add extra data to the stream, perhaps a company versioning code, the possibilities are truly limitless.<br />
<br />
Apart from writeObject and readObject methods, we can also leverage other <a href="https://www.programmingmitra.com/2019/08/java-serialization-magic-methods-and-their-uses-with-example.html" target="_blank">serialization magic methods</a> to get some additional functionality.<br />
<h2>
</h2>
<h2>
Stopping Serialization and Deserialization</h2>
Suppose we have a class which got the serialization capability from its parent, which means our class extends from another class which implements <code>Serializable</code>.<br />
<br />
It means anybody can serialize and deserialize the object of our class. But what if we do not want our class to be serialized or deserialized e.g. our class is a singleton and we want to prevent any new object creation, remember the <a href="https://www.programmingmitra.com/2016/05/different-ways-to-create-objects-in-java-with-example.html">deserialization process creates a new object</a>.<br />
<br />
To stop the serialization for our class, we can once again use the above private methods to just throw the <code>NotSerializableException</code>. Any attempt to serialize or deserialise our object will now always result in the exception being thrown. And since those methods are declared as <code>private</code>, nobody can override your methods and change them.<br />
<br />
<pre><code class="language-java" lang="java">private void writeObject(ObjectOutputStream oos) throws IOException {
throw new NotSerializableException("Serialization is not supported on this object!");
}
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
throw new NotSerializableException("Serialization is not supported on this object!");
}</code></pre>
<h2>
</h2>
<div style="text-align: left;">
<br /></div>
<div style="text-align: left;">
However, this is a violation of the Liskov Substitution Principle. And <a href="https://www.programmingmitra.com/2019/08/java-serialization-magic-methods-and-their-uses-with-example.html" target="_blank"><span style="font-family: monospace;">writeReplace</span> and <span style="font-family: monospace;">readResolve</span> methods can be used</a> to achieve singleton like behaviours. These methods are used to allow an object to provide an alternative representation for itself within an ObjectStream. In simple words, <span style="font-family: monospace;">readResolve</span> can be used to change the data that is deserialized through the readObject method and <span style="font-family: monospace;">writeReplace</span> can be used to change the data that is serialized through writeObject.</div>
<br />
Java <a href="https://www.programmingmitra.com/2019/08/how-to-deep-clone-an-object-using-java-in-memory-serialization.html">serialization can also be used to deep clone an object</a>. Java cloning is the most debatable topic in Java community and it surely does have its drawbacks but it is still the most popular and easy way of creating a copy of an object until that object is full filling mandatory conditions of Java cloning. I have covered cloning in details in a 3 article long <a href="https://programmingmitra.blogspot.in/search/label/Java%20Cloning">Java Cloning Series</a> which includes articles like <a href="https://programmingmitra.blogspot.in/2016/11/Java-Cloning-Types-of-Cloning-Shallow-Deep-in-Details-with-Example.html">Java Cloning And Types Of Cloning (Shallow And Deep) In Details With Example</a>, <a href="https://programmingmitra.blogspot.in/2017/01/Java-cloning-copy-constructor-versus-Object-clone-or-cloning.html">Java Cloning - Copy Constructor Versus Cloning</a>, <a href="https://programmingmitra.blogspot.in/2017/01/java-cloning-why-copy-constructors-are-not-sufficient-or-good.html">Java Cloning - Even Copy Constructors Are Not Sufficient</a>, go ahead and read them if you want to know more about cloning.
<br />
<br />
<h2>
Conclusion</h2>
<ol>
<li><strong>Serialization</strong> is the process of saving an object's state to a sequence of bytes which then can be stored on a file or sent over the network and <strong>deserialization</strong> is the process of reconstructing an object from those bytes.</li>
<li>Only subclasses of the <code>Serializable</code> interface can be serialized.</li>
<li>If our class does not implement <code>Serializable</code> interface or if it is having a reference to a non <code>Serializable</code> class then JVM will throw <code>NotSerializableException</code>.</li>
<li>All <code>transient</code> and <code>static</code> fields do not get serialized.</li>
<li>The <code>serialVersionUID</code> is used to verify that the serialized and deserialized objects have the same attributes and thus are compatible with deserialization.</li>
<li>We should create a <code>serialVersionUID</code> field in our class so if we change our class structure (adding/removing fields) JVM will not through <code>InvalidClassException</code>. If we do not provide it JVM provides one which might change when our class structure changes.</li>
<li>We can override the default serialization behaviour inside our Java class by providing the implementation of <code>writeObject</code> and <code>readObject</code> methods.</li>
<li>And we can call <code>ObjectOutputStream.defaultWriteObject()</code> and <code>ObjectInputStream.defaultReadObject</code> from <code>writeObject</code> and <code>readObject</code> methods to get the default serialization and deserialization logic.</li>
<li>We can throw <code>NotSerializableException</code> exception from <code>writeObject</code> and <code>readObject</code> , if we do not want our class to be serialized or deserialized.</li>
</ol>
Java Serialization process can be further customized and enhanced using the <code>Externalizable</code> interface which I have explained in <a href="https://www.programmingmitra.com/2019/08/how-to-customize-serialization-in-java-by-using-externalizable-interface.html" target="_blank">How to Customize Serialization In Java By Using Externalizable Interface</a>.<br />
<br />
I have also written a series of articles explaining item numbers 74 to 78 of Effective Java, which further discusses how Java serialization process can be enhanced, please go ahead and read them if you like.<br />
<br />
You can find the complete source code for this article on this <a href="https://github.com/njnareshjoshi/exercises/blob/master/src/org/programming/mitra/exercises/SerializationExample.java">Github Repository</a> and please feel free to provide your valuable feedback.<br />
<br /></div>
Naresh Joshihttp://www.blogger.com/profile/01073925481525463593noreply@blogger.com0tag:blogger.com,1999:blog-3832771837877502009.post-67489032813152119802019-03-29T21:02:00.003+05:302020-09-02T22:09:43.363+05:30How to Install Multiple Versions of Java on the Same Machine<div dir="ltr" style="text-align: left;" trbidi="on">
Some time back I have written one article <a href="https://www.programmingmitra.com/2016/06/java-lambda-expression-explained-with-example.html">Java Lambda Expression Explained with Example</a> but it was easy for me to explore and Java 8 because I was using it in my project and I was allowed to install and use it. But in my current project, we are still using Java 8 and now I want to upgrade myself and learn Java 11 but can not install it.<br />
<br />
And this happens with a lot of Java developers, Sometimes you want to learn and explore the latest version of Java e.g. Java 11 but you can not install it on your machine because you and your team is working on some older version e.g. Java 8, and you do not want to break your project.<br />
<br />
Or suppose you are working on multiple projects some of which use Java 8 and some new projects are using Java 11. So in order to work on these projects parallelly, you will need to install multiple JDK on your machine and you should be able to switch between them.<br />
<br />
What if there is a way and what if you are enabled to install multiple versions of Java and turn off and turn on them according to your need.</div><div dir="ltr" style="text-align: left;" trbidi="on"><br /></div><div class="separator" style="clear: both; text-align: center;"><iframe allowfullscreen="" class="BLOG_video_class" height="300" src="https://www.youtube.com/embed/qnFczcDAl_A" width="600" youtube-src-id="qnFczcDAl_A"></iframe></div><br /><div dir="ltr" style="text-align: left;" trbidi="on"><br />
<br />
Well there is a tool called <a href="https://sdkman.io/">SDKMan</a> which allow us to do the same and according to the official website:<br />
<br />
<blockquote>
<strong>SDKMan!</strong> is a tool for managing parallel versions of multiple <strong>Software Development Kits</strong> on most Unix based systems. It provides a convenient Command Line Interface (CLI) and API for installing, switching, removing and listing Candidates.</blockquote>
<br />
Some points about SDKMan are as following:<br />
<ol start="">
<li>SDKMan is free to use and it is developed by the open-source community.</li>
<li>SDKMan is written in <a href="https://www.gnu.org/software/bash/">bash</a> and it only requires <a href="http://curl.haxx.se/">curl</a> and <a href="http://www.info-zip.org/">zip/unzip</a> programs to be present on your system.</li>
<li>SDKMan can install around 29 Software Development Kits for the JVM such as Java, Groovy, Scala, Kotlin and Ceylon. Ant, Gradle, Grails, Maven, SBT, Spark, Spring Boot, Vert.x.</li>
<li>We do not need to worry about setting the <code>_HOME</code> and <code>PATH</code> environment variables because SDKMan handles it automatically.</li>
</ol>
<br />
<h2>
Installing SDKMan</h2>
SDKMan can run on any UNIX based platforms such as Mac OSX, Linux, Cygwin, Solaris and FreeBSD and we can install it using following commands:<br />
<br />
Simply open a new terminal and enter:<br />
<br />
<pre><code class="language-shell" lang="shell">$ curl -s "https://get.sdkman.io" | bash
$ source "$HOME/.sdkman/bin/sdkman-init.sh"
</code></pre>
<br />
We can verify the installation using <code>sdk version</code> and <code>sdk help</code> command will us complete help about the usage of <code>sdk</code> command.<br />
<br />
<blockquote>
Because SDKMan is written in <a href="https://www.gnu.org/software/bash/">bash</a> and only requires <a href="http://curl.haxx.se/">curl</a> and <a href="http://www.info-zip.org/">zip/unzip</a> to be present on your system. You can install SDKMan on windows as well either by first installing <a href="https://www.cygwin.com/install.html">Cygwin</a> or <a href="https://git-scm.com/download/win">Git Bash for Windows</a> environment and then running above commands.</blockquote>
<h2>
</h2>
<h2>
Installing Java Using SDKMan</h2>
SDKMan supports installations of 29 Software Development Kits for the JVM e.g. Java, Groovy, Scala, Kotlin and Ceylon, Grails, SBT, Spark, Spring Boot. We can get the complete list using <code>sdk list</code> command.<br />
<br />
SDKMan also helps us install build tools such as Ant, Maven and Gradle, You can read more about these build tools on <a href="https://www.programmingmitra.com/2016/05/java-build-tools-comparisons-ant-vs.html" target="_blank">Java Build Tools Comparisons: Ant vs Maven vs Gradle</a>.<br />
<br />
Command <code>sdk list java</code> will give us a list of java versions which we can install using SDKMan like below:<br />
<br />
<pre><code class="language-shell" lang="shell">$ sdk list java
================================================================================
Available Java Versions
================================================================================
13.ea.02-open 1.0.0-rc-10-grl
12.ea.26-open 1.0.0-rc-9-grl
11.0.2-zulu 1.0.0-rc-8-grl
11.0.2-open
11.0.1-zulufx
10.0.2-zulu
10.0.2-open
9.0.7-zulu
9.0.4-open
8.0.202-amzn
8.0.201-zulu
8.0.201-oracle
8.0.192-zulufx
7.0.181-zulu
1.0.0-rc-11-grl
================================================================================
+ - local version
* - installed
> - currently in use
================================================================================
</code></pre>
<br />
Now Suppose we want to install OpenJDK version of Java v9 then we will execute below command in our terminal which will also update the PATH and JAVA_HOME variables:<br />
<br />
<pre><code class="language-shell" lang="shell">$ sdk install java 9.0.4-open
</code></pre>
<br />
The command will take some time to execute because it will be downloading the JDK on our machine and the command will output something like:<br />
<br />
<pre><code class="language-shell" lang="shell">Downloading: java 9.0.4-open
In progress...
######################################################################## 100.0%
Repackaging Java 9.0.4-open...
Done repackaging...
Cleaning up residual files...
Installing: java 9.0.4-open
Done installing!
Setting java 9.0.4-open as default.
</code></pre>
<br />
<br />
Now if we check our Java version and JAVA_HOME, we can see Java has been updated to 9.0.4<br />
<br />
<pre><code class="language-shell" lang="shell">$ java -version
openjdk version "9.0.4"
OpenJDK Runtime Environment (build 9.0.4+11)
OpenJDK 64-Bit Server VM (build 9.0.4+11, mixed mode)
$ echo $JAVA_HOME
/Users/xbbnrde/.sdkman/candidates/java/current
</code></pre>
<br />
We can follow the same process to install any version which we can see in the above list, let us suppose we want to install Java V11 version then we can execute the command:<br />
<br />
<pre><code class="language-shell" lang="shell">$ sdk install java 11.0.2-open
Downloading: java 11.0.2-open
In progress...
######################################################################## 100.0%
Repackaging Java 11.0.2-open...
Done repackaging...
Cleaning up residual files...
Installing: java 11.0.2-open
Done installing!
Do you want java 11.0.2-open to be set as default? (Y/n): Y
Setting java 11.0.2-open as default.
</code></pre>
<br />
Now if we again check our Java version and JAVA_HOME, we can see Java has been updated to 11.0.2:<br />
<br />
<pre><code class="language-shell" lang="shell">$ java -version
openjdk version "11.0.2" 2019-01-15
OpenJDK Runtime Environment 18.9 (build 11.0.2+9)
OpenJDK 64-Bit Server VM 18.9 (build 11.0.2+9, mixed mode)
$ echo $JAVA_HOME
/Users/xbbnrde/.sdkman/candidates/java/current</code></pre>
<br />
<blockquote>
Note: Some times you will require to close and reopen your terminal in order to see the changes.</blockquote>
<img alt="sdkman-installing-and-running-java11-and-java-9-simultaneously" border="0" data-original-height="1600" data-original-width="1335" height="800" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEilsDO2uacR0rq8crKlM5Xlfn062OcaKfbE_lEccb5-yLxMP1fkhjrSM9wXNOcTO5_czlR0Q4FGSOi-qAbOJHoYgTHJT8JE5cv1Xr5PE0s57OrRilDDtLkV2y4RyuRvLo03N1GPrnQJfps/w668-h800/sdkman-installing-and-running-java11-and-java-9-simultaneously.jpg" title="sdkman-installing-and-running-java11-and-java-9-simultaneously" width="668" /><br /><br />
<h2>
Pointing SDKMan to your existing installed Java version</h2>
First, we need to find out where on your machine Java is installed. On my machine, it is installed in the folder <code>jdk1.8.0_172.jdk</code> which lies under the folder <code>/Library/Java/JavaVirtualMachines</code>, let's refer to this folder by <code><java-folder></code>.<br />
<br />
The second thing we want to do is to set up a symbolic link between our installed <code><java-folder></code> and SDKMan, we can do it by running below commands:<br />
<br />
<pre><code class="language-shell" lang="shell">$ ln -s /Library/Java/JavaVirtualMachines/<java-folder> ~/.sdkman/candidates/java/<java-folder>
$ sudo ln -s /Library/Java/JavaVirtualMachin</code></pre><pre><code class="language-shell" lang="shell">es/<java-folder>/Contents/Home/bin ~/.sdkman/candidates/java/<java-folder>/bin
</code></pre>
<br />
<br />
Now if we again execute <code>sdk list java</code> command, we will get:<br />
<br />
<pre><code class="language-shell" lang="shell">================================================================================
Available Java Versions
================================================================================
+ jdk1.8.0_172.jd 8.0.201-zulu
13.ea.02-open 8.0.201-oracle
12.ea.26-open 8.0.192-zulufx
11.0.2-zulu 7.0.181-zulu
> * 11.0.2-open 1.0.0-rc-12-grl
11.0.2.j9-adpt 1.0.0-rc-11-grl
11.0.2.hs-adpt 1.0.0-rc-10-grl
11.0.1-zulufx 1.0.0-rc-9-grl
10.0.2-zulu 1.0.0-rc-8-grl
10.0.2-open
9.0.7-zulu
* 9.0.4-open
8.0.202-amzn
8.0.202.j9-adpt
8.0.202.hs-adpt
================================================================================
+ - local version
* - installed
> - currently in use
================================================================================
</code></pre>
<br />
<br />
We can clearly see that we have 3 JDK installed on our machine and JDK <code>11.0.2-open</code> is in use as of now. However, if we want to switch between them or install a new one we can do that very easily by using <code>sdk use java <version_which_you_want_to_use></code> like the following:<br />
<br />
<h4>
Using Java 9</h4>
<pre><code class="language-shell" lang="shell">$ sdk use java 9.0.4-open
Using java version 9.0.4-open in this shell.
$ java -version
openjdk version "9.0.4"
OpenJDK Runtime Environment (build 9.0.4+11)
OpenJDK 64-Bit Server VM (build 9.0.4+11, mixed mode)
</code></pre>
<br />
<h4>
Using locally installed Java 8</h4>
<pre><code class="language-shell" lang="shell">$ sdk use java jdk1.8.0_172.jdk
Using java version jdk1.8.0_172.jdk in this shell.
<table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="font-family: times; margin-left: auto; margin-right: auto; text-align: center;"><tbody><tr><td></td></tr><tr><td class="tr-caption">Add caption</td></tr></tbody></table>
$ java -version
java version "1.8.0_172"
Java(TM) SE Runtime Environment (build 1.8.0_172-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.172-b11, mixed mode)
</code></pre>
<br />
<h4>
Using Java 11</h4>
<pre><code class="language-shell" lang="shell">$ sdk use java 11.0.2-open
Using java version 11.0.2-open in this shell.
$ java -version
openjdk version "11.0.2" 2019-01-15
OpenJDK Runtime Environment 18.9 (build 11.0.2+9)
OpenJDK 64-Bit Server VM 18.9 (build 11.0.2+9, mixed mode)
</code></pre>
<br />
<br />
<blockquote>
Using <code>sdk use</code> command will only enable you to use a specified version of JDK in the same terminal shell where you are executing the <code>sdk use</code> command. And if you close the terminal and open it again you will be on the previously installed version.</blockquote>
<br />
But if you want to activate one version of JDK for all terminals and applications, you can use the command <code>sdk default java <your_version></code><br />
<br />
<pre><code class="language-shell" lang="shell">$ sdk default java 11.0.2-open
Default java version set to 11.0.2-open
$ java -version
openjdk version "11.0.2" 2019-01-15
OpenJDK Runtime Environment 18.9 (build 11.0.2+9)
OpenJDK 64-Bit Server VM 18.9 (build 11.0.2+9, mixed mode)
</code></pre>
Or you can uninstall that version and install it again like below which will set that version to the current JDK.<br />
<h2>
Uninstalling a JDK Version</h2>
In case you want to uninstall any JDK version e.g., <code>11.0.2-open</code> you can do that as follows:<br />
<br />
<pre><code class="language-shell" lang="shell">$ sdk uninstall java 11.0.2-open
</code></pre>
And in case you want to install the uninstalled version back again, you can install it again and this time SDKMan will not download it because it already has that on your machine (unless you do not delete that manually).<br />
<br />
<pre><code class="language-shell" lang="shell">$ sdk install java 11.0.2-open
Found a previously downloaded java 11.0.2-open archive. Not downloading it again...
Installing: java 11.0.2-open
Done installing!
Do you want java 11.0.2-open to be set as default? (Y/n): y
Setting java 11.0.2-open as default.
</code></pre>
<h2>
Using SDMan installed JDK from IntelliJ IDEA</h2>
SDKMan installs all JDK under <code>.sdkman/candidates/java/</code> folder and you can find <code>.sdkman</code> folder in your home directory.<br />
<br />
After opening any Java project in IntelliJ, you can press <code>Command + :</code> to open the project structure window. In that window, you will need to click on <code>New...</code> under <code>Project SDK</code> section and there you can enter <code>.sdkman/candidates/java/</code> in the browse window and can select any JDK from <code>.sdkman/candidates/java/</code>.<br />
<br />
Because <code>.sdkman</code> is a hidden folder and in case you face some problem in finding it, you can always create a symbolic link to it with a non-hidden folder using below command.<br />
<br />
<pre><code class="language-shell" lang="shell">$ ln -s ~/.sdkman ~/sdkman
</code></pre>
<br />
You can find the complete source code for my articles on this <a href="https://github.com/njnareshjoshi/articles">Github Repository</a> and please feel free to provide your valuable feedback.<br />
<br /></div>
Naresh Joshihttp://www.blogger.com/profile/01073925481525463593noreply@blogger.com2tag:blogger.com,1999:blog-3832771837877502009.post-50756478927974808412019-01-24T23:39:00.003+05:302020-04-14T18:19:16.128+05:30Useful Git Commands<div dir="ltr" style="text-align: left;" trbidi="on">
Git is a most widely used and powerful version control system for tracking changes in computer files and coordinating work on those files among multiple people. It is primarily used for source code management in software development, but it can be used to keep track of changes in any set of files. <br />
<br />
Git was developed by Linus Torvalds in 2005 as a distributed open-source software version control software and of course, it is free to use. As a distributed revision control system it is aimed at speed, data integrity, and support for distributed, non-linear workflows.<br />
<br />
While other version control systems e.g. CVS, SVN keeps most of their data like commit logs on a central server, every git repository on every computer is a full-fledged repository with a complete history and full version tracking abilities, independent of network access or a central server.<br />
<br />
However, almost all IDEs support git out of the box and we do not require submitting the git commands manually but it is always good to understand these commands. Below is a list of some git commands to work efficiently with git. <br />
<br />
<h2>
Git Help</h2>
The most useful command in git is <code>git help</code> which provides us with all the help we require. If we type <code>git help</code> in the terminal, we will get:<br />
<br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEizGr16LJVhc8CMH9-vrS0qj7qm-C-Cs-p8d9oMkEJdF6DHhnK8_-JjfUkMiTCg5QCBzgImeRDdLZsamMByWM5oyenLojHkSHLGDNz2ZzB7ji93WiPfg-9r0-HH1Y4CC8-MTATgyPm7UYI/s1600/useful-git-commands.png"><img alt="useful-git-commands" border="0" height="522" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEizGr16LJVhc8CMH9-vrS0qj7qm-C-Cs-p8d9oMkEJdF6DHhnK8_-JjfUkMiTCg5QCBzgImeRDdLZsamMByWM5oyenLojHkSHLGDNz2ZzB7ji93WiPfg-9r0-HH1Y4CC8-MTATgyPm7UYI/s640/useful-git-commands.png" title="useful-git-commands" width="640" /></a><br />
<br />
Command <code>git help -a</code> will give us a complete list of git commands:<br />
<pre><code class="language-shell" lang="shell">Available git commands in '/usr/local/git/libexec/git-core'
add gc receive-pack
add--interactive get-tar-commit-id reflog
am grep remote
annotate gui remote-ext
apply gui--askpass remote-fd
archimport gui--askyesno remote-ftp
archive gui.tcl remote-ftps
askpass hash-object remote-http
bisect help remote-https
bisect--helper http-backend repack
blame http-fetch replace
branch http-push request-pull
bundle imap-send rerere
cat-file index-pack reset
check-attr init rev-list
check-ignore init-db rev-parse
check-mailmap instaweb revert
check-ref-format interpret-trailers rm
checkout log send-email
checkout-index ls-files send-pack
cherry ls-remote sh-i18n--envsubst
cherry-pick ls-tree shortlog
citool mailinfo show
clean mailsplit show-branch
clone merge show-index
column merge-base show-ref
commit merge-file stage
commit-tree merge-index stash
config merge-octopus status
count-objects merge-one-file stripspace
credential merge-ours submodule
credential-manager merge-recursive submodule--helper
credential-store merge-resolve subtree
credential-wincred merge-subtree svn
cvsexportcommit merge-tree symbolic-ref
cvsimport mergetool tag
daemon mktag unpack-file
describe mktree unpack-objects
diff mv update
diff-files name-rev update-git-for-windows
diff-index notes update-index
diff-tree p4 update-ref
difftool pack-objects update-server-info
difftool--helper pack-redundant upload-archive
fast-export pack-refs upload-pack
fast-import patch-id var
fetch prune verify-commit
fetch-pack prune-packed verify-pack
filter-branch pull verify-tag
fmt-merge-msg push web--browse
for-each-ref quiltimport whatchanged
format-patch read-tree worktree
fsck rebase write-tree
fsck-objects rebase--helper
</code></pre>
<br />
And command <code>git help -g</code> will give us a list of git concepts which git think is good for us:<br />
<pre><code class="language-shell" lang="shell">The common Git guides are:
attributes Defining attributes per path
everyday Everyday Git With 20 Commands Or So
glossary A Git glossary
ignore Specifies intentionally untracked files to ignore
modules Defining submodule properties
revisions Specifying revisions and ranges for Git
tutorial A tutorial introduction to Git (for version 1.5.1 or newer)
workflows An overview of recommended workflows with Git
</code></pre>
<br />
We can use <code>git help <command></code> or <code>git help <concept></code> command to know more about a specific command or concept.<br />
<br />
<h2>
Git Configuration</h2>
<br />
<br />
<figure><table border="1px">
<thead>
<tr><th>Description</th><th>Git Command</th></tr>
</thead>
<tbody>
<tr><td>List all configurations applied to the current repository in order (picked from bottom to top).</td><td><span style="font-family: monospace;">git config --list Or git config --global --list </span></td></tr><tr><td>Configure the author name to be used with your commits by replacing old entries.</td><td><code>git config --global --replace-all user.name "Sam Smith"</code></td></tr>
<tr><td>Configure the author email address to be used with your commits</td><td><code>git config --global user.email sam@example.com</code></td></tr>
<tr><td>Will remove user credential details from the repository</td><td><code>git config --local credential.helper ""</code></td></tr>
<tr><td>List all currently configured remote repository URLs</td><td><code>git remote -v</code></td></tr>
<tr><td>If you haven't connected your local repository to a remote server, To add a remote server to a local repository</td><td><code>git remote add origin <repo_url></code></td></tr>
</tbody>
</table>
</figure>
<br />
<br />
<h2>
Git Commit and Push</h2>
<br />
<br />
<figure><table border="1px">
<thead>
<tr><th>Description</th><th>Git Command</th></tr>
</thead>
<tbody>
<tr><td>Create a file name <code>README.md</code> with <code>Readme content</code> content</td><td><code>echo "Readme content" >> README.md</code></td></tr>
<tr><td>List the files you've changed and those you still need to add or commit</td><td><code>git status</code></td></tr>
<tr><td>Add all or one file to the staging area</td><td><code>git add .</code> OR <code>git add folder/file_name</code></td></tr><tr><td>Remove all or one file from the staging area </td><td> <code>git reset HEAD</code> OR <code>git reset HEAD folder/file_name</code></td></tr>
<tr><td>Commit changes to head with a message</td><td><code>git commit -m 'message'</code></td></tr>
<tr><td>Commit any files you've added with <code>git add</code>, and also commit any files you've changed since then</td><td><code>git commit -a</code></td></tr>
<tr><td>Send all commits from local repository to remote repository</td><td><code>git push</code></td></tr>
<tr><td>Do a <code>git push</code> and sets the default remote branch for the current local branch. So any future <code>git pull</code> command will attempt to bring in commits from the <code><remote-branch></code>into the current local branch</td><td><code>git push -u <remote-branch></code></td></tr>
<tr><td>Send changes to the master branch of your remote repository</td><td><code>git push origin master</code></td></tr>
<tr><td>Push a specific branch to your remote repository</td><td><code>git push origin <branch_name></code></td></tr>
<tr><td>Push all branches to your remote repository</td><td><code>git push --all origin</code></td></tr>
</tbody>
</table>
</figure>
<br />
<br />
<h2>
Git Checkout And Pull</h2>
<br />
<br />
<figure><table border="1px">
<thead>
<tr><th>Description</th><th>Git Command</th></tr>
</thead>
<tbody>
<tr><td>To create a new local repository</td><td><code>git init</code></td></tr>
<tr><td>Clone a repository into a new directory</td><td><code>git clone repo_url</code></td></tr>
<tr><td>Clone a repository into a new directory and point to mentioned <code>branch_name</code></td><td><code>git clone --branch branch_name repo_url</code></td></tr>
<tr><td>To create a working copy of a local repository</td><td><code>git clone /path/to/repository</code></td></tr>
<tr><td>Download objects and refs from a remote repository for the master branch</td><td><code>git fetch origin master</code></td></tr>
<tr><td>To merge a different branch into your active branch</td><td><code>git merge <branch_name></code></td></tr>
<tr><td>Fetch and merge changes on the remote server to your working directory:</td><td><code>git pull</code></td></tr>
<tr><td>View all the merge conflicts, View the conflicts against the base file, Preview changes, before merging</td><td><code>git diff</code>, <code>git diff --base <filename></code>, <code>git diff <sourcebranch> <targetbranch></code></td></tr>
</tbody>
</table>
</figure>
<br />
<br />
<h2>
Git Branch</h2>
<br />
<br />
<figure><table border="1px">
<thead>
<tr><th>Description</th><th>Git Command</th></tr>
</thead>
<tbody>
<tr><td>List all the branches in your repository, and also tell you what branch you're currently in</td><td><code>git branch</code></td></tr>
<tr><td>Switch from one branch to another</td><td><code>git checkout branch_name</code></td></tr>
<tr><td>Create a new branch and switch to it</td><td><code>git checkout -b branch_name</code></td></tr>
<tr><td>Create a new branch from the master branch and switch to it</td><td><code>git checkout -b branch_name master</code></td></tr>
<tr><td>Delete the feature branch from the local repository</td><td><code>git branch -d <branch_name></code></td></tr>
<tr><td>Delete a branch on your remote repository</td><td><code>git push origin :<branch_name></code></td></tr>
</tbody>
</table>
</figure>
<br />
<br />
<h2>
Git Cleaning</h2>
<br />
<br />
<figure><table border="1px">
<thead>
<tr><th>Description</th><th>Git Command</th></tr>
</thead>
<tbody>
<tr><td>Fetch the latest history (objects & refs) from the remote server for the master branch</td><td><code>git fetch origin master</code></td></tr>
<tr><td>Clean the repository to the last push </td><td><code>git clean -x -d -f</code></td></tr>
<tr><td>Reset local repository and point your local master branch to latest history fetched from the remote server</td><td><code>git reset --hard origin/master</code></td></tr>
<tr><td>To bring all changes from a remote repository to the local repository</td><td><code>git pull origin master</code></td></tr>
</tbody>
</table>
</figure>
<br />
<br />
<h2>
Other Git commands</h2>
<br />
<br />
<figure><table border="1px">
<thead>
<tr><th>Description</th><th>Git Command</th></tr>
</thead>
<tbody>
<tr><td>You can use tagging to mark a significant changeset, such as a release</td><td><code>git tag 1.0.0 <commitID></code></td></tr>
<tr><td>Commit Id is the leading characters of the changeset ID, up to 10, but must be unique. Get the ID using</td><td><code>git log</code></td></tr>
<tr><td>Push all tags to the remote repository</td><td><code>git push --tags origin</code></td></tr>
<tr><td>If you mess up, you can replace the changes in your working tree with the last content in head: Changes already added to the index, as well as new files, will be kept</td><td><code>git checkout -- <filename></code></td></tr>
<tr><td>Search the working directory for <code>foo()</code></td><td><code>git grep "foo()"</code></td></tr>
</tbody>
</table>
</figure>
<br />
I keep these commands as notes for my future reference and you can find more on this <a href="https://github.com/njnareshjoshi/articles/blob/master/useful-git-commands/UsefulGitCommands.md">Github Repository</a> and please feel free to provide your valuable feedback.</div>
Naresh Joshihttp://www.blogger.com/profile/01073925481525463593noreply@blogger.com0tag:blogger.com,1999:blog-3832771837877502009.post-68297383293422306962018-11-25T22:22:00.003+05:302020-09-02T22:11:51.823+05:30Java Integer Cache - Why Integer.valueOf(127) == Integer.valueOf(127) Is True<div dir="ltr" style="text-align: left;" trbidi="on">
In an interview, one of my friends was asked that if we have two Integer objects, <code>Integer a = 127; Integer b = 127;</code> Why <code>a == b</code> evaluate to <code>true</code> when both are holding two separate objects? In this article, I will try to answer this question and also try to explain the answer.<br />
<br />
<h4>
Short Answer</h4>
The short answer to this question is, direct assignment of an <code>int</code> literal to an <code>Integer</code> reference is an example of auto-boxing concept where the literal value to object conversion code is handled by the compiler, so during compilation phase compiler converts <code>Integer a = 127;</code> to <code>Integer a = Integer.valueOf(127);</code>.<br />
<br />
The <code>Integer</code> class maintains an internal <span style="font-family: monospace;">IntegerCache</span> for integers which by default ranges from <code>-128 to 127</code> and <code>Integer.valueOf()</code> method returns objects of mentioned range from that cache. So <code>a == b</code> returns true because <code>a</code> and <code>b</code> both are pointing to the same object.</div><div dir="ltr" style="text-align: left;" trbidi="on"><br /></div><div class="separator" style="clear: both; text-align: center;"><iframe allowfullscreen="" class="BLOG_video_class" height="300" src="https://www.youtube.com/embed/rkpDuCFB_bQ" width="600" youtube-src-id="rkpDuCFB_bQ"></iframe></div><div dir="ltr" style="text-align: left;" trbidi="on"><br />
<h4>
Long Answer</h4>
In order to understand the short answer let's first understand the Java types, all types in Java lies under two categories<br />
<br />
<ol start="">
<li><strong>Primitive Types:</strong> There are 8 primitive types (byte, short, int, long, float, double, char and boolean) in Java which holds their values directly in the form of binary bits.<br />For example, <code>int a = 5; int b = 5;</code> here <code>a</code> and <code>b</code> directly holds the binary value of 5 and if we try to compare <code>a</code> and <code>b</code> using <code>a == b</code> we are actually comparing <code>5 == 5</code> which returns true.<br />
<br />
</li>
<li><strong>Reference Types:</strong> All types other than primitive types lies under the category of reference types e.g. Classes, Interfaces, Enums, Arrays etc. and reference types holds the address of the object instead of the object itself.<br />For example, <code>Integer a = new Integer(5); Integer b = new Integer(5)</code>, here a and b do not hold the binary value of <code>5</code> instead <code>a</code> and <code>b</code> holds memory addresses of two separate objects where both objects contain a value <code>5</code>. So if we try to compare <code>a</code> and <code>b</code> using <code>a == b, </code>we are actually comparing those two separate memory addresses hence we get <code>false</code>, to perform actual equality on <code>a</code> and <code>b</code> we need to perform <code>a.euqals(b)</code>.<br />
<br />
<blockquote>
Reference types are further divided into 4 categories <a href="https://programmingmitra.com/2016/05/types-of-references-in-javastrong-soft.html" target="_blank">Strong, Soft, Weak and Phantom References</a>.</blockquote>
</li>
</ol>
<br />
And we know that Java provides wrapper classes for all primitive types and support auto-boxing and auto-unboxing.<br />
<br />
<pre><code class="language-java" lang="java">// Example of auto-boxing, here c is a reference type
Integer c = 128; // Compiler converts this line to Integer c = Integer.valueOf(128);
// Example of auto-unboxing, here e is a primitive type
int e = c; // Compiler converts this line to int e = c.intValue();
</code></pre>
<br />
Now if we create two integer objects <code>a</code> and <code>b,</code> and try to compare them using the equality operator <code>==</code>, we will get <code>false</code> because both references are holding different-different objects<br />
<br />
<pre><code class="language-java" lang="java">Integer a = 128; // Compiler converts this line to Integer a = Integer.valueOf(128);
Integer b = 128; // Compiler converts this line to Integer b = Integer.valueOf(128);
System.out.println(a == b); // Output -- false
</code></pre>
<br />
But if we assign the value <code>127</code> to both <code>a</code> and <code>b</code> and try to compare them using the equality operator <code>==</code>, we will get <code>true</code> why?<br />
<br />
<pre><code class="language-java" lang="java">Integer a = 127; // Compiler converts this line to Integer a = Integer.valueOf(127);
Integer b = 127; // Compiler converts this line to Integer b = Integer.valueOf(127);
System.out.println(a == b); // Output -- true
</code></pre>
<br />
As we can see in the code that we are assigning different objects to <code>a</code> and <code>b</code> but <code>a == b</code> can return true only if both <code>a</code> and <code>b</code> are pointing to the same object.<br />
<br />
So how the comparison returning true? what's actually happening here? are <code>a</code> and <code>b</code> pointing to the same object?<br />
<br />
Well till now we know that the code <code>Integer a = 127;</code> is an example of auto-boxing and compiler automatically converts this line to <code>Integer a = Integer.valueOf(127);</code>.<br />
<br />
So it is the <code>Integer.valueOf()</code> method which is returning these integer objects which means this method must be doing something under the hood.<br />
<br />
And if we take a look at the source code of <code>Integer.valueOf()</code> method, we can clearly see that if the passed int literal <code>i</code> is greater than <code>IntegerCache.low</code> and less than <code>IntegerCache.high </code>then the method returns Integer objects from <code>IntegerCache</code>. Default values for <code>IntegerCache.low</code> and <code>IntegerCache.high</code> are <code>-128</code> and <code>127</code> respectively.<br />
<br />
In other words, instead of creating and returning new integer objects, <code>Integer.valueOf()</code> method returns Integer objects from an internal <code>IntegerCache</code> if the passed int literal is greater than <code>-128</code> and less than <code>127</code>.<br />
<br />
<pre><code class="language-java" lang="java">/**
* Returns an {@code Integer} instance representing the specified
* {@code int} value. If a new {@code Integer} instance is not
* required, this method should generally be used in preference to
* the constructor {@link #Integer(int)}, as this method is likely
* to yield significantly better space and time performance by
* caching frequently requested values.
*
* This method will always cache values in the range -128 to 127,
* inclusive, and may cache other values outside of this range.
*
* @param i an {@code int} value.
* @return an {@code Integer} instance representing {@code i}.
* @since 1.5
*/
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
</code></pre>
<br />
Java caches integer objects which fall into -128 to 127 range because this range of integers gets used a lot in day to day programming which indirectly saves some memory.<br />
<br />
As you can see in the following image <code>Integer</code> class maintains an inner static <code>IntegerCache</code> class which acts as the cache and holds integer objects from -128 to 127 and that's why when we try to get integer object for <code>127</code> we always get the same object.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgatYxoEJND_dbjHfpfYqS0GfvNI4OD5Q-zo-vVrNK6qgvT7_2zz7bjJsoypITOFqI64I2KRQZ7DVVFeBKxXfdDO3a7FWVnlFZIQntBVMG9xqjfNQJLeVMFXDz0HCI84FANC6qoKzsOAtE/s1600/integer-cache-src-code.jpeg" style="margin-left: 1em; margin-right: 1em;"><img alt="integer-cache-source-code" border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgatYxoEJND_dbjHfpfYqS0GfvNI4OD5Q-zo-vVrNK6qgvT7_2zz7bjJsoypITOFqI64I2KRQZ7DVVFeBKxXfdDO3a7FWVnlFZIQntBVMG9xqjfNQJLeVMFXDz0HCI84FANC6qoKzsOAtE/s1600/integer-cache-src-code.jpeg" title="integer-cache-sourcec-code" /></a></div>
<br />
<br />
The cache is initialized on the first usage when the class gets loaded into memory because of the <code>static block</code>. The max range of the cache can be controlled by the <code>-XX:AutoBoxCacheMax</code> JVM option.<br />
<br />
This caching behavior is not applicable to <code>Integer</code> objects only, similar to <code>Integer.IntegerCache</code> we also have <code>ByteCache</code>, <code>ShortCache</code>, <code>LongCache</code>, <code>CharacterCache</code> for <code>Byte</code>, <code>Short</code>, <code>Long</code>, <code>Character</code> respectively.<br />
<br />
Byte, Short and Long have a fixed range for caching between –127 to 127 (inclusive) but for Character, the range is from 0 to 127 (inclusive). The range can be modified via argument only for Integer but not for others.<br />
<br />
You can find the complete source code for this article on this <a href="https://github.com/njnareshjoshi/exercises/blob/master/src/org/programming/mitra/exercises/IntegerCacheExample.java" target="_blank">Github Repository</a> and please feel free to provide your valuable feedback.</div>
Naresh Joshihttp://www.blogger.com/profile/01073925481525463593noreply@blogger.com3tag:blogger.com,1999:blog-3832771837877502009.post-42244021906923622892018-11-09T19:25:00.003+05:302020-09-05T17:58:05.329+05:30Why Instance Variable Of Super Class Is Not Overridden In Sub Class<div dir="ltr" style="text-align: left;" trbidi="on">
When we create a variable in both parent and child class with the same name, and try to access it using parent's class reference which is holding a child class's object then what do we get?<br />
<br />
In order to understand this, let us consider below example where we declare a variable <code>x</code> with the same name in both <code>Parent</code> and <code>Child</code> classes.<br />
<br />
<pre><code class="language-java" lang="java">class Parent {
// Declaring instance variable by name `x`
String x = "Parent`s Instance Variable";
public void print() {
System.out.println(x);
}
}
class Child extends Parent {
// Hiding Parent class's variable `x` by defining a variable in child class with same name.
String x = "Child`s Instance Variable";
@Override
public void print() {
System.out.print(x);
// If we still want to access variable from super class, we do that by using `super.x`
System.out.print(", " + super.x + "\n");
}
}
</code></pre>
<br />
<br />
And now if we try to access <code>x</code> using below code, what <code>System.out.println(parent.x)</code> will print<br />
<br />
<br />
<pre><code class="language-java" lang="java">Parent parent = new Child();
System.out.println(parent.x) // Output -- Parent`s Instance Variable
</code></pre>
<br />
<br />
Well generally, we will say <code>Child</code> class will override the variable declared in the <code>Parent</code> class and <code>parent.x</code> will give us whatever <code>Child's</code> object is holding. Because it is the same thing which happens while we do same kind of operation on methods.<br />
<br />
But actually it is not, and <code>parent.x</code> will give us value <span style="font-family: monospace;">Parent`s Instance Variable</span> which is declared in <code>Parent</code> class but why?<br />
<br />
Because variables in Java do not follow polymorphism and overriding is only applicable to methods but not to variables. And when an instance variable in a child class has the same name as an instance variable in a parent class, then the instance variable is chosen from the reference type.<br />
<br />
In Java, when we define a variable in Child class with a name which we have already used to define a variable in the Parent class, Child class's variable hides parent's variable, even if their types are different. And this concept is known as <strong>Variable Hiding.</strong><br />
<br />
In other words, when the child and parent class both have a variable with the same name, Child class's variable hides the parent class's variable. You can read more on variable hiding in the article <a href="https://programmingmitra.com/2018/02/what-is-variable-shadowing-and-hiding.html" target="_blank">What is Variable Shadowing and Hiding in Java</a>.</div><div dir="ltr" style="text-align: left;" trbidi="on"><br /></div><div dir="ltr" style="text-align: left;" trbidi="on"><br /></div><div class="separator" style="clear: both; text-align: center;"><iframe allowfullscreen="" class="BLOG_video_class" height="320" src="https://www.youtube.com/embed/-FJp9vTw7kM" width="640" youtube-src-id="-FJp9vTw7kM"></iframe></div><br /><div dir="ltr" style="text-align: left;" trbidi="on"><br />
<br />
<h2>
Variable Hiding is not the same as Method Overriding</h2>
While variable hiding looks like overriding a variable similar to method overriding but it is not, overriding is applicable only to methods while hiding is applicable to variables.<br />
<br />
In the case of <strong>method overriding</strong>, overriding methods completely replaces the inherited methods so when we try to access the method from parent's reference by holding child's object, the method from child class gets called. You can read more about overriding and how overridden methods completely replace the inherited methods on <a href="https://programmingmitra.com/2017/05/everything-about-method-overloading-vs-method-overriding.html" target="_blank">Everything About Method Overloading Vs Method Overriding</a>, <a href="https://programmingmitra.com/2017/12/why-we-should-follow-method-overriding-rules.html" target="_blank">Why We Should Follow Method Overriding Rules</a>.<br />
<br />
But in <strong>variable hiding</strong> child class hides the inherited variables instead of replacing which basically means is that the object of Child class contains both variables but Child's variable hides Parent's variable. so when we try to access the variable from within Child class, it will be accessed from the child class.<br />
<br />
And if I simplify section <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#d5e10238">Example 8.3.1.1-3. Hiding of Instance Variables</a> of <a href="http://docs.oracle.com/javase/specs/jls/se7/html/index.html">Java language specification</a>:<br />
<br />
<blockquote>
When we declare a variable in a <code>Child</code> class which has the same name e.g. <code>x</code> as an instance variable in a <code>Parent</code> class then<br />
<ol>
<li>Child class's object contains both variables (one inherited from <code>Parent</code> class and other declared in <code>Child</code> itself) but child class variable hides parent class's variable.</li>
<li>Because the declaration of <code>x</code> in class <code>Child</code> hides the definition of <code>x</code> in class <code>Parent</code>, within the declaration of class <code>Child</code>, the simple name <code>x</code> always refers to the field declared within class <code>Child</code>. And if code in methods of <code>Child</code> class want to refer to the variable <code>x</code> of <code>Parent</code> class then this can be done as <code>super.x</code>.</li>
<li>If we are trying to access the variable outside of <code>Parent</code> and <code>Child</code> class, then the instance variable is chosen from the reference type. Thus, the expression <code>parent2.x</code> in following code gives the variable value which belongs to parent class even if it is holding the object of the <code>Child</code> but <code>((Child) parent2).x</code> accesses the value from the <code>Child</code> class because we casted the same reference to <code>Child</code>.</li></ol></blockquote>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjTtwIUOjN6uyPmFgi6pXvZ8ZgvZKsKzpNmXZ5bVMSdja6Lu41sEsg7vcp1FUNoRIhIfdH9qGNVw-PsbiCIzbxDOMl7WQmCAsNeAo8rKrcmPHFz6X6ufUqMhBfmh8gsIT8FRdkDisq9Av4/s1600/variable-shadowing.jpeg" style="margin-left: 1em; margin-right: 1em;"><img alt="Why Instance Variable Of Super Class Is Not Overridden In Sub Class due to variable shadowing" border="0" height="274" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjTtwIUOjN6uyPmFgi6pXvZ8ZgvZKsKzpNmXZ5bVMSdja6Lu41sEsg7vcp1FUNoRIhIfdH9qGNVw-PsbiCIzbxDOMl7WQmCAsNeAo8rKrcmPHFz6X6ufUqMhBfmh8gsIT8FRdkDisq9Av4/w640-h274/variable-shadowing.jpeg" title="Why Instance Variable Of Super Class Is Not Overridden In Sub Class due to variable shadowing" width="640" /></a></div>
<br />
<h2>
Why Variable Hiding Is Designed This Way</h2>
<strong>So we know that instance variables are chosen from the reference type, not instance type, and polymorphism is not applicable to variables</strong> but the real question is why? why variables are designed to follow hiding instead of overriding.<br />
<br />
Because variable overriding might break methods inherited from the parent if we change its type in the child class.<br />
<br />
We know every child class inherits variables and methods (state and behaviour) from its parent class. Imagine if Java allows variable overriding and we change the type of a variable from <code>int</code> to <code>Object</code> in the child class. It will break any method which is using that variable and because the child has inherited those methods from the parent, the compiler will give errors in <code>child</code> class.<br />
<br />
For example:<br />
<br />
<pre><code class="language-java" lang="java">class Parent {
int x;
public int increment() {
return ++x;
}
public int getX() {
return x;
}
}
class Child extends Parent {
Object x;
// Child is inherting increment(), getX() from Parent and both methods returns an int
// But in child class type of x is Object, so increment(), getX() will fail to compile.
}
</code></pre>
<br />
If <code>Child.x</code> overrides <code>Parent.x</code>, how can <code>increment()</code> and <code>getX()</code> work? In the subclass, these methods will try to return a value of a field of the wrong type!<br />
<br />
And as mentioned, if Java allows variable overriding then Child's variable cannot substitute Parent's variable and this would break the Liskov Substitutability Principle (LSP).<br />
<br />
<h2>
Why Instance Variable Is Chosen from Reference Type Instead Of Instance</h2>
<div>
As explained in <a href="https://programmingmitra.com/2017/05/how-does-jvm-handle-method-overriding-internally.html" target="_blank">How Does JVM Handle Method Overloading and Overriding Internally</a>, at compile time overriding method calls are treated from the reference class only but all overridden methods get replaced by the overriding method at the runtime using a vtable and this phenomenon is called runtime polymorphism.</div>
<div>
<br /></div>
<div>
Similarly, at compile time variable access is also treated from the reference type but as we discussed variables do not follow overriding or runtime polymorphism, so they are not replaced by child class variables at the runtime and still refer to the reference type.</div>
<div>
<br /></div>
<br />
Generally speaking, nobody will ever recommend hiding fields as it makes code difficult to read and creates confusion. This kind of confusion will not there if we always stick to <a href="https://programmingmitra.com/2016/05/plain-old-java-object-pojo-explained.html" target="_blank">General Guidelines to create POJOs</a> and encapsulate our fields by declaring them as private and provides getters/setters as required so the variables are not visible outside that class and child class cannot access them.<br />
<br />
You can find complete code on this <a href="https://github.com/njnareshjoshi/exercises/blob/master/src/org/programming/mitra/exercises/VariableShadowingExample.java" target="_blank">Github Repository</a> and please feel free to provide your valuable feedback.</div>
Naresh Joshihttp://www.blogger.com/profile/01073925481525463593noreply@blogger.com0tag:blogger.com,1999:blog-3832771837877502009.post-23910043513357402372018-07-28T13:05:00.002+05:302019-01-15T21:17:49.420+05:30Spring Modular Architecture<div dir="ltr" style="text-align: left;" trbidi="on">
In a previous article <a href="https://programmingmitra.com/2016/05/introduction-to-spring.html" target="_blank">Introduction to Spring</a>, we discussed What is Spring and why it so popular among Java developers and we also discussed how Spring has broken its complete framework into different-different modules based on the functionality.<br />
<br />
Spring framework is organized into <strong>20 modules</strong> which can again be grouped into <strong>Core Container, Web, Data Access/Integration, AOP, Aspect, Instrumentation, Messaging, and Test</strong>, as shown in the following diagram.<br />
<img alt="spring-modules" src="https://lh6.googleusercontent.com/xeNVkYHP8yQ3NZoRxQ8J6DPdd9pPs7l7pXK6YsNcnzqSjaVvwsa2acBeJ9pi6ad3geT9PnEdGcGmVD8_KgjsGdVcLySohIrBFYVQdo7xLdqyThU1LV-I5WYgLUSdhPB51u6Dp95r0sY2WsHHWQ" title="spring-modules" /><br />
<h2>
Core container</h2>
The <b>Core and Beans modules</b> provide the most fundamental parts of the framework and provide the IoC and Dependency Injection features. The basic concept here is the <code>BeanFactory</code>which provides a sophisticated implementation of the factory pattern. It removes the need for programmatic singletons and allows you to decouple the configuration and specification of dependencies from your actual program logic.<br />
<br />
The <b>Context module</b> builds on the solid base provided by the Core and Beans modules: it provides a way to access objects in a framework-style manner in a fashion somewhat reminiscent of a JNDI-registry. The Context module inherits its features from the Beans module and adds support for internationalization (I18N) (using for example resource bundles), event-propagation, resource-loading, and the transparent creation of contexts by, for example, a servlet container. The Context module also contains support for some Java EE features like EJB, JMX, and basic remoting support. The <code>ApplicationContext</code> interface is the focal point of the Context module that provides these features.<br />
<br />
The <b>Expression Language module</b> provides a powerful expression language for querying and manipulating an object graph at runtime. It can be seen as an extension of the unified expression language (unified EL) as specified in the JSP 2.1 specification. The language supports setting and getting of property values, property assignment, method invocation, accessing the context of arrays, collections, and indexers, logical and arithmetic operators, named variables, and retrieval of objects by name from Spring's IoC container. It also supports list projection and selection, as well as common list aggregators.<br />
<br />
<h2>
Spring Web module</h2>
Spring's <b>Web module</b> provides basic web-oriented integration features, such as multipart file-upload functionality, the initialization of the IoC container using servlet listeners and a web-oriented application context. It also contains the web-related parts of Spring's remoting support.<br />
<br />
The <b>Web-Servlet module</b> provides Spring's Model-View-Controller implementation for web-applications. Spring MVC framework is a full-featured MVC implementation for building Web applications. The MVC framework is highly configurable via strategy interfaces and accommodates numerous view technologies including JSP, Velocity, Tiles, iText, and POI. We can also create Rest APIs using the same annotation as we use in web MVC.<br />
<br />
The <b>Web-Portlet module</b> provides the MVC implementation to be used in a portlet environment and mirrors what is provided in the Web-Servlet module.<br />
<br />
<h2>
Data Access & Integration</h2>
The Data Access/Integration layer consists of the JDBC, ORM, OXM, JMS and Transaction modules.<br />
<br />
The <b>JDBC module</b> provides a JDBC-abstraction layer that removes the need to do tedious JDBC coding and parsing of database-vendor specific error codes.<br />
<br />
The <b>ORM module</b> provides integration layers for popular object-relational mapping APIs, including JPA, JDO, Hibernate, and iBatis. Using the ORM package you can use all those O/R-mappers in combination with all the other features Spring offers, such as the simple declarative transaction management feature mentioned previously.<br />
<br />
The <b>OXM module</b> provides an abstraction layer for using a number of Object/XML mapping implementations. Supported technologies include JAXB, Castor, XMLBeans, JiBX, and XStream.<br />
<br />
The <b>JMS module</b> provides Spring's support for the Java Messaging Service. It contains features for both producing and consuming messages.<br />
<br />
The <b>Transaction module</b> provides a way to do programmatic as well as declarative transaction management, not only for classes implementing special interfaces but for all your <a href="https://programmingmitra.com/2016/05/plain-old-java-object-pojo-explained.html" target="_blank">POJOs (plain old Java objects)</a>.<br />
<h2>
Spring AOP and Aspect</h2>
The Spring AOP module integrates Aspect Oriented Programming functionality directly into the Spring framework, which allows us to define segregate our cross-cutting functionalities from our business logic. As a result, we can easily AOP-enable any object managed by the Spring framework. The Spring AOP module provides transaction management services for objects in any Spring-based application.<br />
<br />
There is also a separate <b>Aspects</b> module that provides integration with AspectJ.<br />
<br />
<h2>
Instrumentation</h2>
The <b>Instrumentation module</b> provides class instrumentation support and classloader implementations to be used in certain application servers.<br />
<br />
<h2>
Messaging</h2>
Spring framework's messaging module serves as a foundation for messaging-based applications. The module provides a set of classes e.g., <code>Message, </code><code>MessageChannel</code><code>MessageHandler</code> to send and receive messages from the application and it also provides a set of annotations for mapping messages to methods, similar to the Spring MVC annotation based programming model.<br />
<br />
<h2>
Test</h2>
Spring framework's Test module provides abstraction over a lot of testing and mocking framework such as TestNG, JUnit, Mockito, PowerMock which makes writing unit and integration a lot easier.<br />
<br />
Below are the dependencies for the above modules<br />
<br />
<table cellpadding="0" cellspacing="0" class="t1">
<tbody>
<tr>
<td class="td1" valign="top"><div class="p2">
<span class="s2"><b>GroupId</b></span></div>
</td>
<td class="td2" valign="top"><div class="p2">
<span class="s2"><b>ArtifactId</b></span></div>
</td>
<td class="td3" valign="top"><div class="p2">
<span class="s2"><b>Description</b></span></div>
</td>
</tr>
<tr>
<td class="td4" valign="top"><div class="p2">
<span class="s2">org.springframework</span></div>
</td>
<td class="td5" valign="top"><div class="p2">
<span class="s2">spring-aop</span></div>
</td>
<td class="td6" valign="top"><div class="p2">
<span class="s2">Proxy-based AOP support</span></div>
</td>
</tr>
<tr>
<td class="td7" valign="top"><div class="p2">
<span class="s2">org.springframework</span></div>
</td>
<td class="td8" valign="top"><div class="p2">
<span class="s2">spring-aspects</span></div>
</td>
<td class="td9" valign="top"><div class="p2">
<span class="s2">AspectJ based aspects</span></div>
</td>
</tr>
<tr>
<td class="td4" valign="top"><div class="p2">
<span class="s2">org.springframework</span></div>
</td>
<td class="td5" valign="top"><div class="p2">
<span class="s2">spring-beans</span></div>
</td>
<td class="td6" valign="top"><div class="p2">
<span class="s2">Beans support, including Groovy</span></div>
</td>
</tr>
<tr>
<td class="td7" valign="top"><div class="p2">
<span class="s2">org.springframework</span></div>
</td>
<td class="td8" valign="top"><div class="p2">
<span class="s2">spring-context</span></div>
</td>
<td class="td9" valign="top"><div class="p2">
<span class="s2">Application context runtime, including scheduling and remoting abstractions</span></div>
</td>
</tr>
<tr>
<td class="td4" valign="top"><div class="p2">
<span class="s2">org.springframework</span></div>
</td>
<td class="td5" valign="top"><div class="p2">
<span class="s2">spring-context-support</span></div>
</td>
<td class="td6" valign="top"><div class="p2">
<span class="s2">Support classes for integrating common third-party libraries into a Spring application context</span></div>
</td>
</tr>
<tr>
<td class="td7" valign="top"><div class="p2">
<span class="s2">org.springframework</span></div>
</td>
<td class="td8" valign="top"><div class="p2">
<span class="s2">spring-core</span></div>
</td>
<td class="td9" valign="top"><div class="p2">
<span class="s2">Core utilities, used by many other Spring modules</span></div>
</td>
</tr>
<tr>
<td class="td4" valign="top"><div class="p2">
<span class="s2">org.springframework</span></div>
</td>
<td class="td5" valign="top"><div class="p2">
<span class="s2">spring-expression</span></div>
</td>
<td class="td6" valign="top"><div class="p2">
<span class="s2">Spring Expression Language (SpEL)</span></div>
</td>
</tr>
<tr>
<td class="td7" valign="top"><div class="p2">
<span class="s2">org.springframework</span></div>
</td>
<td class="td8" valign="top"><div class="p2">
<span class="s2">spring-instrument</span></div>
</td>
<td class="td9" valign="top"><div class="p2">
<span class="s2">Instrumentation agent for JVM bootstrapping</span></div>
</td>
</tr>
<tr>
<td class="td4" valign="top"><div class="p2">
<span class="s2">org.springframework</span></div>
</td>
<td class="td5" valign="top"><div class="p2">
<span class="s2">spring-instrument-tomcat</span></div>
</td>
<td class="td6" valign="top"><div class="p2">
<span class="s2">Instrumentation agent for Tomcat</span></div>
</td>
</tr>
<tr>
<td class="td7" valign="top"><div class="p2">
<span class="s2">org.springframework</span></div>
</td>
<td class="td8" valign="top"><div class="p2">
<span class="s2">spring-jdbc</span></div>
</td>
<td class="td9" valign="top"><div class="p2">
<span class="s2">JDBC support package, including DataSource setup and JDBC access support</span></div>
</td>
</tr>
<tr>
<td class="td4" valign="top"><div class="p2">
<span class="s2">org.springframework</span></div>
</td>
<td class="td5" valign="top"><div class="p2">
<span class="s2">spring-jms</span></div>
</td>
<td class="td6" valign="top"><div class="p2">
<span class="s2">JMS support package, including helper classes to send/receive JMS messages</span></div>
</td>
</tr>
<tr>
<td class="td7" valign="top"><div class="p2">
<span class="s2">org.springframework</span></div>
</td>
<td class="td8" valign="top"><div class="p2">
<span class="s2">spring-messaging</span></div>
</td>
<td class="td9" valign="top"><div class="p2">
<span class="s2">Support for messaging architectures and protocols</span></div>
</td>
</tr>
<tr>
<td class="td4" valign="top"><div class="p2">
<span class="s2">org.springframework</span></div>
</td>
<td class="td5" valign="top"><div class="p2">
<span class="s2">spring-orm</span></div>
</td>
<td class="td6" valign="top"><div class="p2">
<span class="s2">Object/Relational Mapping, including JPA and Hibernate support</span></div>
</td>
</tr>
<tr>
<td class="td7" valign="top"><div class="p2">
<span class="s2">org.springframework</span></div>
</td>
<td class="td8" valign="top"><div class="p2">
<span class="s2">spring-oxm</span></div>
</td>
<td class="td9" valign="top"><div class="p2">
<span class="s2">Object/XML Mapping</span></div>
</td>
</tr>
<tr>
<td class="td4" valign="top"><div class="p2">
<span class="s2">org.springframework</span></div>
</td>
<td class="td5" valign="top"><div class="p2">
<span class="s2">spring-test</span></div>
</td>
<td class="td6" valign="top"><div class="p2">
<span class="s2">Support for unit testing and integration testing Spring components</span></div>
</td>
</tr>
<tr>
<td class="td7" valign="top"><div class="p2">
<span class="s2">org.springframework</span></div>
</td>
<td class="td8" valign="top"><div class="p2">
<span class="s2">spring-tx</span></div>
</td>
<td class="td9" valign="top"><div class="p2">
<span class="s2">Transaction infrastructure, including DAO support and JCA integration</span></div>
</td>
</tr>
<tr>
<td class="td4" valign="top"><div class="p2">
<span class="s2">org.springframework</span></div>
</td>
<td class="td5" valign="top"><div class="p2">
<span class="s2">spring-web</span></div>
</td>
<td class="td6" valign="top"><div class="p2">
<span class="s2">Foundational web support, including web client and web-based remoting</span></div>
</td>
</tr>
<tr>
<td class="td7" valign="top"><div class="p2">
<span class="s2">org.springframework</span></div>
</td>
<td class="td8" valign="top"><div class="p2">
<span class="s2">spring-webmvc</span></div>
</td>
<td class="td9" valign="top"><div class="p2">
<span class="s2">HTTP-based Model-View-Controller and REST endpoints for Servlet stacks</span></div>
</td>
</tr>
<tr>
<td class="td4" valign="top"><div class="p2">
<span class="s2">org.springframework</span></div>
</td>
<td class="td5" valign="top"><div class="p2">
<span class="s2">spring-webmvc-portlet</span></div>
</td>
<td class="td6" valign="top"><div class="p2">
<span class="s2">MVC implementation to be used in a Portlet environment</span></div>
</td>
</tr>
<tr>
<td class="td10" valign="top"><div class="p2">
<span class="s2">org.springframework</span></div>
</td>
<td class="td11" valign="top"><div class="p2">
<span class="s2">spring-websocket</span></div>
</td>
<td class="td12" valign="top"><div class="p2">
<span class="s2">WebSocket and SockJS infrastructure, including STOMP messaging support</span></div>
</td>
</tr>
</tbody>
</table>
</div>
Naresh Joshihttp://www.blogger.com/profile/01073925481525463593noreply@blogger.com4tag:blogger.com,1999:blog-3832771837877502009.post-73416360930688525322018-02-17T14:27:00.000+05:302019-01-15T21:38:58.158+05:30How to Create an Immutable Class in Java with Example<div dir="ltr" style="text-align: left;" trbidi="on">
In order to create an object, we need to define a class that's why the class is called the blueprint of the object and an immutable class is a class which we can use to create immutable objects.<br />
<br />
<h2>
What is an immutable object</h2>
An object is called immutable if its state cannot be modified by anyone in any way after its construction, here object's state means the fields or the variables it is holding.<br />
<br />
An immutable object does not expose its state to the outer world and neither provides any behaviour to modify its state. All wrapper classes i.e <code>Integer</code>, <code>Float</code>, <code>Long</code> are immutable in nature and other examples of immutable classes are <code>String</code>, <code>java.util.UUID</code>, <code>java.net.URL</code>.<br />
<br />
<h2>
Advantages of immutable objects</h2>
In <a href="https://programmingmitra.com/2018/02/why-string-is-immutable-and-final-in-java.html" target="_blank">Why String is Immutable and Final in Java</a>, I have discussed how just by being immutable in nature, <span style="font-family: monospace;">String </span>gains lots of advantages including<br />
<ol style="text-align: left;">
<li>Thread Safety, </li>
<li>Hash-code caching,</li>
<li>Object pool,</li>
<li>Security.</li>
</ol>
<div>
Same advantages are applied to other immutable objects as well.<br />
<br /></div>
<h2>
How to create a class for an immutable object</h2>
To create an immutable object we need to define our class in a way that it restricts every one (including itself) from changing the state of the object after its construction, and in order to do so we need to<br />
<ol>
<li>Mark your class final,</li>
<li>Mark all the fields private,</li>
<li>Mark all fields final as well,</li>
<li>Provide an argument constructor with all initialization logic,</li>
<li>Initialize all mutable fields by deep copying,</li>
<li>Do not provide setters for your fields,</li>
<li>Return a deep copy of mutable fields from the getters.</li>
</ol>
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhZasPptlrKpl-NbftB9vSwEZgeus208ADJG3xZemiYppMMrd2dE-yVtjTC6k4FxI1bMDKtTwilmmW-4JlggD9xt33nVaPX_Ma1vL6Xrybn_2am-XqpP97sl2zMEkLXwnQS2MzVJwNjQdQ/s1600/How-to-Create-an-Immutable-Class-in-Java-with-Example.JPG" imageanchor="1"><img alt="How-to-Create-an-Immutable-Class-in-Java-with-Example" border="0" height="370" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhZasPptlrKpl-NbftB9vSwEZgeus208ADJG3xZemiYppMMrd2dE-yVtjTC6k4FxI1bMDKtTwilmmW-4JlggD9xt33nVaPX_Ma1vL6Xrybn_2am-XqpP97sl2zMEkLXwnQS2MzVJwNjQdQ/s640/How-to-Create-an-Immutable-Class-in-Java-with-Example.JPG" title="How-to-Create-an-Immutable-Class-in-Java-with-Example" width="640" /></a><br />
<br />
Let's look at all these rules and the reasons to follow them<br />
<br />
<h3>
1. Why mark our class final</h3>
We should declare our class final to forbids its extension so no one can extend our class and destroy its immutability. If it is not final then in future someone might extend it and modify the behaviour to change the state.<br />
<br />
<h3>
2. Why mark all the fields private</h3>
We should mark all the fields private so no one can access them outside of the class.<br />
<br />
<h3>
3. Why mark all fields final as well</h3>
Mark all the fields final so even we will not be able to change the fields outside of the constructor.<br />
<br />
<h3>
4. Why provide an argument constructor with all initialization logic</h3>
A constructor is a place to write our object initialization logic because constructor gets called whenever we create an object.<br />
<br />
So when we want to set our object's state during object creation only, we need to set it in the constructor and that's why we need to have an argument constructor in case of an immutable class.<br />
<br />
As discussed in <a href="https://programmingmitra.com/2016/05/different-ways-to-create-objects-in-java-with-example.html" target="_blank">5 different ways to create objects</a> and <a href="https://programmingmitra.com/2016/05/creating-objects-through-reflection-in-java-with-example.html" target="_blank">creating objects through reflection</a>, serialization and <a href="https://programmingmitra.com/search/label/Java%20Cloning" target="_blank">cloning</a> also create new objects but both of them does not include a constructor call. But we do not need to worry about it because in both ways object will be constructed from an already present object which will be already immutable in nature.<br />
<br />
<h3>
5. Why initialize all mutable fields by deep copying</h3>
If our immutable object holds a reference to other immutable objects i.e. <code>String, Integer</code> we do not need to worry because we know they will not allow any change in their state.<br />
<br />
But if our object holds references to some mutable objects and those mutable objects are also getting referred from somewhere else, in that case, our object's immutability is in danger.<br />
<br />
In our example, our <code>ImmutableEmployee</code> class holds a reference to <code>Date</code> class which is mutable in nature. In below lines of code we are creating a variable <code>dob</code> which is holding a Date object and then we are passing it to <code>ImmutableEmployee's</code> constructor and creating an object which is being referred from <code>employee</code>.<br />
<br />
<pre><code>Date dob = new Date();
ImmutableEmployee employee = new ImmutableEmployee(1, "Naresh", dob);
</code></pre>
<br />
When we <code>SysOut</code> employee object we will get<br />
<br />
<pre><code>ImmutableEmployee{id=1, name='Naresh', dob=Sun Jan 10 00:12:00 IST 1993}
</code></pre>
<br />
Now if we do not initialize <code>dob</code> fields by deep copying then both <code>dob</code> and <code>employee.dob</code> will point to a single object and if we change anything in <code>dob,</code> <code>employee.dob</code> will also reflect that change which means <code>employee</code> object will become mutable.<br />
<br />
But by deep copying <code>dob</code> field both <code>employee.dob</code> and <code>dob</code> will point to two different objects and we will not face this problem, as you can see output of below code<br />
<br />
<pre><code>dob.setMonth(1);
System.out.println(dob); // Prints - Wed Feb 10 00:12:00 IST 1993
System.out.println(employee.getDob()); // Prints - Sun Jan 10 00:12:00 IST 1993
System.out.println(employee); // Prints - ImmutableEmployee{id=1, name='Naresh', dob=Sun Jan 10 00:12:00 IST 1993}
</code></pre>
<br />
In our example, I have used the copy constructor <code>this.dob = new Date(dob.getTime());</code> to copy our objects because there are some basic problems with Java cloning and we can not sure of either it is a deep copy or shallow copy without seeing cloning code of that class.<br />
<br />
You can read more about cloning, cloning types and why copy constructors are better than on more detailed articles such as <a href="https://programmingmitra.com/2016/11/Java-Cloning-Types-of-Cloning-Shallow-Deep-in-Details-with-Example.html" target="_blank">Java Cloning And Types Of Cloning (Shallow and Deep)</a>, <a href="https://programmingmitra.com/2017/01/Java-cloning-copy-constructor-versus-Object-clone-or-cloning.html" target="_blank">Java Cloning - Copy Constructor Versus Cloning</a> and <a href="https://programmingmitra.com/2017/01/java-cloning-why-copy-constructors-are-not-sufficient-or-good.html" target="_blank">Java Cloning - Even Copy Constructors Are Not Sufficient</a>.<br />
<br />
<h3>
6. Why should not provide setters for your fields</h3>
Well, providing setters will allow us to modify the state of the object which we do not want.<br />
<br />
<h3>
7. Why return a deep copy of mutable fields instead of returning objects from the getters.</h3>
If we return all mutable fields directly, we will face the same scenario as discussed in point 5 and after executing below code both <code>employee.dob</code> and <code>temp</code> will point to the same object, now if we make any change in <code>temp</code>, <code>employee.dob</code> will also change which again means <code>employee</code> will not remain immutable.<br />
<br />
So instead of returning mutable fields, we should return their deep copy and as we have done that, we can see in below code <code>employee</code> remains same and immutable at the end.<br />
<br />
<pre><code>Date temp = employee.getDob();
temp.setMonth(2);
System.out.println(temp); // Prints - Wed Mar 10 00:12:00 IST 1993
System.out.println(employee.getDob()); // Prints - Sun Jan 10 00:12:00 IST 1993
System.out.println(employee); // Prints - ImmutableEmployee{id=1, name='Naresh', dob=Sun Jan 10 00:12:00 IST 1993}
</code></pre>
<br />
In the end, I wanted to say that all immutable objects in Java are effective immutable not completely immutable because <a href="https://programmingmitra.com/2018/02/why-string-is-immutable-and-final-in-java.html" target="_blank">we can modify them using reflection</a>.<br />
<br />
Below is the complete source code to create an immutable class which you can also find on this <a href="https://github.com/njnareshjoshi/exercises/blob/master/src/org/programming/mitra/exercises/ImmutableClassExample.java" target="_blank">Github Repository</a> and please feel free to provide your valuable feedback.<br />
<br />
<pre><code>// 1. Declare your class as final, So other classes can't extend it and break its immutability
final class ImmutableEmployee {
// 2. Make all your fields private they can't be accessed outside your class
// 3. Mark them as final so no one can modify them anywhere else apart from the constructor, if you do not have any specific requirement to not do so
private final int id;
private final String name;
private final Date dob;
// 4. Create an constructor with argument so you can assign instantiate your object with a proper state
public ImmutableEmployee(int id, String name, Date dob) {
this.id = id;
this.name = name;
// 5. Initialise all your fields by deeply copying them if they are not immutable in nature
this.dob = new Date(dob.getTime());
}
// 6. Do not provide setters for your fields, or define them private if you have some requirement
public int getId() {
return id;
}
public String getName() {
return name;
}
// 7. Instead of returning objects from the getters return deep copy them if your objects are not immutable
public Date getDob() {
return new Date(dob.getTime());
}
@Override
public String toString() {
return "ImmutableEmployee{" +
"id=" + id +
", name='" + name + '\'' +
", dob=" + dob +
'}';
}
}
public class ImmutableClassExample {
public static void main(String[] args) throws ParseException {
Date dob = new SimpleDateFormat("dd-mm-yyyy").parse("10-12-1993");
ImmutableEmployee employee = new ImmutableEmployee(1, "Naresh", dob);
System.out.println(employee); // Prints - ImmutableEmployee{id=1, name='Naresh', dob=Sun Jan 10 00:12:00 IST 1993}
dob.setMonth(1);
System.out.println(dob); // Prints - Wed Feb 10 00:12:00 IST 1993
Date temp = employee.getDob();
temp.setMonth(2);
System.out.println(temp); // Prints - Wed Mar 10 00:12:00 IST 1993
System.out.println(employee.getDob()); // Prints - Sun Jan 10 00:12:00 IST 1993
System.out.println(employee); // Prints - ImmutableEmployee{id=1, name='Naresh', dob=Sun Jan 10 00:12:00 IST 1993}
}
}
</code></pre>
<br />
<br /></div>
Naresh Joshihttp://www.blogger.com/profile/01073925481525463593noreply@blogger.com15tag:blogger.com,1999:blog-3832771837877502009.post-11671052979672998332018-02-17T11:13:00.000+05:302019-01-15T21:40:54.667+05:30Why String is Immutable and Final in Java<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
While coding in any programming language we always require some predefined types which we can use to write the code and every programming language provides these types in its way e.g. Java provides primitive types (<code>int, long, char float</code> etc) and reference types (custom types like <code>Object, String, Thread</code>).<br />
<br />
For string manipulation, Java provides a class <code>java.lang.String</code> which gives us a way to create string objects and provides different behaviors to operate on those objects e.g. <code>replace(), length()</code><br />
<code><br /></code>
<br />
<pre><code>String name = "Naresh";
System.out.print(name.length());
System.out.print(name.isEmpty());
</code></pre>
<br />
Whenever we talk about <code>String</code> class in Java we say it is i<strong>mmutable</strong> in nature and all string literals are stored in <strong>String Constant Pool (SCP)</strong>.<br />
<br />
<blockquote>
Prior to Java 7 String Constant Pool belongs to Permanent Generation area of heap which means Garbage Collector will not touch it in normal scenarios. But from Java 7 onwards string constant pool is not part of Perm Gen but live with out in heap which means now unused String objects will get garbage collected.</blockquote>
<br />
And in order to become a good developer, we should always know why these kinds of design decisions were taken. I mean, we should know why <code>String</code> is immutable or why string objects stored in SCP.<br />
<br />
In <a href="https://programmingmitra.com/2018/02/why-string-is-stored-in-constant-pool.html" target="_blank">Why String is Stored in String Constant Pool</a> article, I have discussed why string objects are stored in a separate memory area called constant pool and in this article, I will discuss why String class was made immutable.<br />
<br />
<h1>
String is Effective Immutable not Completely Immutable</h1>
In normal scenarios, String objects are immutable and can't be modified but we can modify them by using Java reflection API. Every string object holds a <code>char[]</code> array as a private variable which actually holds every character from our string.<br />
<br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiUnT28hCThlDglDAG0id3Xjx8c7Zi-lHqZP-ZL_ewa6J8CBdnqmbUaojxTWuZy_Zmh2NKnrNTg8fpUXrEUueJxwuHvqdlp0zraLqzlrdxLXaWCyI_xDxLdbx48FPDZfxa2KomTY2qs6Ao/s1600/why-string-is-immutableand-final-in-java.JPG" imageanchor="1"><img alt="why-string-is-immutable-and-final-in-java" border="0" height="296" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiUnT28hCThlDglDAG0id3Xjx8c7Zi-lHqZP-ZL_ewa6J8CBdnqmbUaojxTWuZy_Zmh2NKnrNTg8fpUXrEUueJxwuHvqdlp0zraLqzlrdxLXaWCyI_xDxLdbx48FPDZfxa2KomTY2qs6Ao/s640/why-string-is-immutableand-final-in-java.JPG" title="why-string-is-immutable-and-final-in-java" width="640" /></a><br />
<br />
Due to the private nature of the <code>char[]</code> array, we cannot access it from outside of string object and none of the string methods modifies it.<br />
<br />
But we can access this <code>char[]</code> array via reflection and then modify it, And that's why instead of calling String immutable we can call it <b>Effective Immutable</b>.<br />
<br />
<pre><code>String string = "Naresh";
Class<String> type = String.class;
Field field = type.getDeclaredField("value");
field.setAccessible(true);
char[] value = (char[]) field.get(string);
value[0] = 'M'; // No `string` variable becomes `Maresh`</code></pre>
<div>
<code><br /></code></div>
<br />
<h1>
Why String is Final</h1>
As discussed in <a href="https://programmingmitra.com/2018/02/how-to-create-immutable-class-in-java.html" target="_blank">How to Create an Immutable Class in Java</a>, in order to make a class immutable we need to make sure no one extends our class and destroy its immutability.<br />
<br />
So String is made <code>final</code> to not allow others to extend it and destroy its immutability.<br />
<br />
<h1>
Why String is Immutable</h1>
However we can not be sure of what was Java designers actually thinking while designing <code>String</code> but we can only conclude these reasons based on the advantages we get out of string immutability, Some of which are as follows.<br />
<br />
<h3>
1. The existence of String Constant Pool</h3>
As discussed in <a href="https://programmingmitra.com/2018/02/why-string-is-stored-in-constant-pool.html" target="_blank">Why String is Stored in String Constant Pool</a>, In order provide a business functionality, every application creates too many string objects and in order to save JVM from first creating lots of string objects and then garbage collecting them. JVM stores all string objects in a separate memory area called String constant pool and reuses objects from that cached pool.<br />
<br />
Whenever we create a string literal JVM first sees if that literal is already present in constant pool or not and if it is there, the new variable will start pointing to the same object in SCP this process is called <b>String Interning</b>.<br />
<br />
<pre><code>String a = "Naresh";
String b = "Naresh";
String c = "Naresh";
</code></pre>
<br />
In above example string object with value <code>Naresh</code> will get created in SCP only once and all variables <code>a</code>, <code>b</code>, <code>c</code> will point to the same object but what if we try to make change in <code>a</code> e.g. <code>a.replace("a", "")</code>.<br />
<br />
Ideally <code>a</code> should have value <code>Nresh</code> but <code>b</code>, <code>c</code> should remain unchanged because as the end user we are making change in <code>a</code> only. And as a developer we know <code>a</code>, <code>b</code>, <code>c</code> all are pointing the same object so if we make a change in <code>a</code>, others should also reflect the change.<br />
<br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg1wlme6xYZvbrfZjiXP027TEBBbtEFFuZfuMOIQT24AE3c80DG92bRMVEyoglTOxLYnqJfdiZ_5dWo75B7rXewDjDgUoIUcMUQ8dvwupblpfC6khMcvnLs43tCwOQvx0rvCHxTrpzn0uc/s1600/string-constant-pool-in-java.JPG" imageanchor="1"><img alt="string-constant-pool-in-java" border="0" height="266" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg1wlme6xYZvbrfZjiXP027TEBBbtEFFuZfuMOIQT24AE3c80DG92bRMVEyoglTOxLYnqJfdiZ_5dWo75B7rXewDjDgUoIUcMUQ8dvwupblpfC6khMcvnLs43tCwOQvx0rvCHxTrpzn0uc/s640/string-constant-pool-in-java.JPG" title="string-constant-pool-in-java" width="640" /></a><br />
<br />
But String's immutability saves us from this scenario and due to which object <code>Naresh</code> will never change. So when we make any change in <code>a,</code> JVM will create a new object assign it to <code>a</code>, and then make the change to that object instead of changing object <code>Naresh</code>.<br />
<br />
So having a string pool is only possible because of String's immutability and if String would not have been immutable, then caching string objects and reusing them would not have been a possibility because any variable would have changed the value and corrupted others.<br />
<br />
<h3>
2. Thread Safety</h3>
An object is called thread-safe when multiple threads are operating on it but none of them is able to corrupt its state and object holds the same state for every thread at any point in time.<br />
<br />
As we know an immutable object cannot be modified by anyone after its creation which makes every immutable object thread safe by default. We do not need to apply any thread safety measures to it such as creating synchronized methods.<br />
<br />
So due to its immutable nature string object can be shared by multiple threads and even if it is getting manipulated by many threads it will not change its value.<br />
<br />
<h3>
3. Security</h3>
In every application, we need to pass several secrets e.g. user's user-name\passwords, connection URLs and in general, all of this information is passed as string objects.<br />
<br />
Now suppose if String would not have been immutable in nature then it could cause serious security threats to the application because these values will be allowed to get changed and if it is allowed then these might get changed due to wrongly written code or by any other person who has access to our variable references.<br />
<br />
<h3>
4. Class Loading</h3>
As discussed in <a href="https://programmingmitra.com/2016/05/creating-objects-through-reflection-in-java-with-example.html" target="_blank">Creating objects through Reflection in Java with Example</a>, we can use <code>Class.forName("class_name")</code> method to load a class in memory which again calls other methods to do so and even JVM uses these methods to load classes.<br />
<br />
But if you see clearly all of these methods accepts the class name as a string object so Strings are used in java class loading and String's immutability makes sure that correct class is getting loaded by <code>ClassLoader</code>.<br />
<br />
Suppose if String would not have been immutable and we are trying to load <code>java.lang.Object</code> which get changed to <code>org.theft.OurObject</code> in between and now all of our objects have a behavior which someone can use to do unwanted things.<br />
<br />
<h3>
5. HashCode Caching</h3>
If we are going to perform any hashing related operations on our object we must override the <code>hashCode()</code> method and try to generate an accurate hashcode by using the state of the object. If object's state is getting changed which means its hashcode should also change.<br />
<br />
Because String is immutable so the value one string object is holding will never get changed which means its hashcode will also not change which gives String class an opportunity to cache its hashcode during object creation.<br />
<br />
Yes, String object caches its hashcode at the time of object creation which makes it a great candidate for hashing related operations because hashcode doesn't need to be calculated again and again which save us some time and this is why String is the most suitable candidate to be used as <code>HashMap</code> keys.<br />
<br />
<h1>
Disadvantages of String Immutability</h1>
<div>
<br /></div>
<div>
There are always two sides to a coin, whenever something is providing us some benefits it will also a have some drawbacks and String's immutability also falls into it.</div>
<div>
<br /></div>
<h3>
1. PermGen Space Error</h3>
Due to the immutability of String, string object can't be changed and whenever we make a change on it, JVM creates a new string object. So if there are 10000 string object in an application and every string object is getting manipulated 10 times then we are left with 110000 string objects.<br />
<br />
And as we know strings are stored in a separate constant pool which is part of Permanent Generation, which usually occupies very limited memory as compared to young and old generations. Having too many String literals will quickly fill this space, resulting in <code>java.lang.OutOfMemoryError: PermGen Space</code> error.<br />
<h3>
</h3>
<h3>
2. Keeping passwords in memory for a long time</h3>
In general, passwords are stored as strings and strings are stored in the constant pool which is exempted from normal garbage collection cycles. So our password might remain in memory for very long time and someone can take advantage of it.<br />
<br />
This is the reason standards suggest to hold password in an <code>char[]</code> array instead of the string object.<br />
<br />
<h3>
3. String is not extensible</h3>
Making String final is part of making it immutable but it also becomes a disadvantage because it limits its extensibility and we cannot extend String to provide more functionality.<br />
<br />
For some developers, it becomes a problem when they require some extra behavior for their string objects but it's not a disadvantage and it can be tacked by creating a utility method which accepts the string as a parameter.<br />
<br />
You can find complete code on this <a href="https://github.com/njnareshjoshi/exercises/blob/master/src/org/programming/mitra/exercises/StringImmutabilityExample.java" target="_blank">Github Repository</a> and please feel free to provide your valuable feedback.<br />
<br /></div>
<br /></div>
Naresh Joshihttp://www.blogger.com/profile/01073925481525463593noreply@blogger.com21tag:blogger.com,1999:blog-3832771837877502009.post-46985677727332727472018-02-17T11:10:00.003+05:302019-03-25T14:45:13.690+05:30Why String is Stored in String Constant Pool<div dir="ltr" style="text-align: left;" trbidi="on">
In a previous article <a href="https://programmingmitra.com/2018/02/why-string-is-immutable-and-final-in-java.html" target="_blank">Why String is Immutable and Final in Java</a>, I have discussed why String is immutable in nature and advantages and disadvantages String's immutability gives us.<br />
<br />
I have also discussed that, all String literals are cached into a special memory area called String Constant Pool and how String's immutability made String constant pool possible.<br />
<br />
But the question arises why do Java required a separate constant pool to store Strings, What's the reason, Why strings are not stored in the normal heap memory like other objects do and in this article,<span style="background-color: #f6d5d9;"> </span>I will try to answer these questions.<br />
<br />
<h2>
String Interning</h2>
Well, we know String is the most popular type present in Java and almost all Java programs use it. In fact, I have not seen a single Java program which is written without using String.<br />
<br />
In general, a normal Java business application deals with thousands of string objects, lots of them have the same value associated and lots of them are mid operations string means they are not the final result.<br />
<br />
So if we store all those string objects in normal heap memory, lot's of the heap will be acquired by just string objects only, and the garbage collector will have to run more frequently which will decrease the performance of the application.<br />
<br />
And that's why we have String Constant Pool and String interning process, whenever we create a string literal JVM first sees if that literal is already present in the constant pool or not and if it is there, the new variable will start pointing to the same object, this process is called <strong>String Interning</strong>.<br />
<br />
There are two ways to create a String object<br />
<ol>
<li>
<strong>Creating String Literal:</strong>: Anything which comes under <code>""</code> is a string literal e.g. <code>String s1 = "Naresh"</code>, by default all string literals interned and goes to SCP.</li>
</ol>
<ol>
<li>
<strong>Creating a String object using constructor:</strong> If we create a String object using the constructor e.g. <code>String s2 = new String("Naresh")</code>, the object is created in normal heap memory instead of SCP. And that's why creating String object using constructor is not considered a best practice. We can ask s2 to point to SCP instead of normal heap manually by calling <code>intern()</code> method on it i.e. s2.intern().</li>
</ol>
So in order to <b>save memory consumed by string objects</b>, Java allows more than one reference variable to point to the same object if they have the same value. That's why JVM creators have created a separate memory area SCP for string literals and made a rule that if more than one string variable holding same value than they will point to the same object.<br />
<br />
<pre><code>String a = "Naresh";
String b = "Naresh";
String c = "Naresh";
</code></pre>
<br />
For above code there will be only one object <code>Naresh</code> will be created and all reference variables <code>a</code>, <code>b</code>, <code>c</code> will point to the same object.<br />
<br />
In above example string object with value <code>Naresh</code> will get created in SCP only once and all reference <code>a</code>, <code>b</code>, <code>c</code> will point to same object but what if we try to make a change in <code>a</code> e.g. <code>a.replace("a", "")</code>.<br />
<br />
Ideally, <code>a</code> should have value <code>Nresh</code> but <code>b</code>, <code>c</code> should remain unchanged because as an end user we are making the change in <code>a</code> only. And we know <code>a</code>, <code>b</code>, <code>c</code> all are pointing the same object so if we make a change in <code>a</code>, others should also reflect the change.<br />
<br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiGETuo7e8ulOEDFwEQA_eimdrPq-Ut8gMDiimW0ZAr_AAxKP-7vVl5bBcIPeC-I3_wt5kj86mjPNCx__xtLmkjw6sIxZgERF0xZ3lV3ULo8BMcvvkAtsEwVSUnliw1O25c17LWxhSNZPM/s1600/string-constant-pool-in-java.JPG" imageanchor="1"><img alt="string-constant-pool-in-java" border="0" height="266" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiGETuo7e8ulOEDFwEQA_eimdrPq-Ut8gMDiimW0ZAr_AAxKP-7vVl5bBcIPeC-I3_wt5kj86mjPNCx__xtLmkjw6sIxZgERF0xZ3lV3ULo8BMcvvkAtsEwVSUnliw1O25c17LWxhSNZPM/s640/string-constant-pool-in-java.JPG" title="string-constant-pool-in-java" width="640" /></a><br />
<br />
But string immutability saves us from this scenario and due to the immutability of string object string object <code>Naresh</code> will never change. So when we make any change in <code>a</code> instead of change in string object <code>Naresh</code> JVM creates a new object assign it to <code>a</code> and then make the change in that object.<br />
<br />
So String pool is only possible because of String's immutability and if String would not have been immutable, then caching string objects and reusing them would not have a possibility because any variable would have changed the value and corrupted others.<br />
<br />
You can find complete code on this <a href="https://github.com/njnareshjoshi/exercises/blob/master/src/org/programming/mitra/exercises/StringImmutabilityExample.java" target="_blank">Github Repository</a> and please feel free to provide your valuable feedback.<br />
<br /></div>
Naresh Joshihttp://www.blogger.com/profile/01073925481525463593noreply@blogger.com2tag:blogger.com,1999:blog-3832771837877502009.post-48480136355133216632018-02-10T13:25:00.000+05:302019-01-26T13:13:51.093+05:30What is Variable Shadowing and Hiding in Java<div dir="ltr" style="text-align: left;" trbidi="on">
Java allows us to declare a variable whenever we need it, We can categorize all our variables into 3 categories which have different-different scopes<br />
<ol>
<li><b>Instance Variables</b> - are defined inside a class and have object level scope.</li>
<li><b>Class Variables</b> - are defined inside a class with static keyword, these variables have a class level scope and are common to all objects of the same class</li>
<li><b>Local Variables</b> - are defined inside a method or in any conditional block, have the block-level scope and only accessible in the block where it defined.</li>
</ol>
<div>
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj6lTXl7B8IIv6PyY0som5RdOf0ExlWNOI_h_FuD70-JlR6r7VO-vsCU0_pZVY3ta8PUQNHdwp83SJDu1J7PEl4tLYOlSaW_aEPnWQqQCTZJv5J8ObyYmLQoQXorMWHSd7KwynUG6qthBo/s1600/what-is-variable-hiding-shadowing.JPG" imageanchor="1"><img alt="what-is-variable-hiding-shadowing" border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj6lTXl7B8IIv6PyY0som5RdOf0ExlWNOI_h_FuD70-JlR6r7VO-vsCU0_pZVY3ta8PUQNHdwp83SJDu1J7PEl4tLYOlSaW_aEPnWQqQCTZJv5J8ObyYmLQoQXorMWHSd7KwynUG6qthBo/s1600/what-is-variable-hiding-shadowing.JPG" title="what-is-variable-hiding-shadowing" /></a></div>
<div class="separator" style="clear: both; text-align: center;">
</div>
<div>
<br /></div>
<h2>
What is Variable Shadowing</h2>
Variable shadowing happens when we define a variable in a closure scope with a variable name and we have already defined a variable in outer scope with the same name.<br />
<br />
In other words, when a local variable has the same name as one of the instance variable, the local variable shadows the instance variable inside the method block.<br />
<br />
In the following example, there is an instance variable named <code>x</code> and inside method <code>printLocalVariable(),</code> we are shadowing it by the local variable <code>x</code>.<br />
<br />
<pre><code>class Parent {
// Declaring instance variable by name `x`
String x = "Parent`s Instance Variable";
public void printInstanceVariable() {
System.out.println(x);
}
public void printLocalVariable() {
// Shadowing instance variable `x` by a local variable with same name
String x = "Local Variable";
System.out.println(x);
// If we still want to access instance variable, we do that by using `this.x`
System.out.println(this.x);
}
}
</code></pre>
<br />
<h2>
What is variable Hiding</h2>
Variable Hiding happens when we define a variable in child class with a variable name which we have already used to define a variable in the parent class. A child class can declare a variable with the same name as an inherited variable from its parent class, thus hiding the inherited variable.<br />
<br />
In other words, when the child and parent class both have a variable with same name child class's variable hides parent class's variable.<br />
<br />
In the below example, we are hiding the variable named <code>x</code> in the child class while it is already defined by its parent class.<br />
<br />
<pre><code>class Child extends Parent {
// Hiding Parent class's variable `x` by defining a variable in child class with same name.
String x = "Child`s Instance Variable";
@Override
public void printInstanceVariable() {
System.out.print(x);
// If we still want to access variable from super class, we do that by using `super.x`
System.out.print(", " + super.x + "\n");
}
}</code></pre>
<h2>
</h2>
<h2>
Variable Hiding is not the same as Method Overriding</h2>
While variable hiding looks like overriding a variable similar to method overriding but it is not, Overriding is applicable only to methods while hiding is applicable variables.<br />
<br />
In the case of method overriding, overridden methods completely replaces the inherited methods so when we try to access the method from parent's reference by holding child's object, the method from child class gets called. You can read more about overriding on <a href="https://programmingmitra.com/2017/05/everything-about-method-overloading-vs-method-overriding.html" target="_blank" title="Everything About Method Overloading Vs Method Overriding">Everything About Method Overloading Vs Method Overriding</a>, <a href="https://programmingmitra.com/2017/12/why-we-should-follow-method-overriding-rules.html" target="_blank" title="Why We Should Follow Method Overriding Rules">Why We Should Follow Method Overriding Rules</a>, <a href="https://programmingmitra.com/2017/05/how-does-jvm-handle-method-overriding-internally.html" target="_blank" title="How Does JVM Handle Method Overloading and Overriding Internally">How Does JVM Handle Method Overloading and Overriding Internally</a>.<br />
<br />
But in variable hiding child class hides the inherited variables instead of replacing, so when we try to access the variable from parent's reference by holding child's object, it will be accessed from the parent class.<br />
<br />
<blockquote>
When an instance variable in a subclass has the same name as an instance variable in a super class, then the instance variable is chosen from the reference type.</blockquote>
<br />
<pre><code>public static void main(String[] args) throws Exception {
Parent parent = new Parent();
parent.printInstanceVariable(); // Output - "Parent`s Instance Variable"
System.out.println(parent.x); // Output - "Parent`s Instance Variable"
Child child = new Child();
child.printInstanceVariable();// Output - "Child`s Instance Variable, Parent`s Instance Variable"
System.out.println(child.x);// Output - "Child`s Instance Variable"
parent = child; // Or parent = new Child();
parent.printInstanceVariable();// Output - "Child`s Instance Variable, Parent`s Instance Variable"
System.out.println(parent.x);// Output - Parent`s Instance Variable
// Accessing child's variable from parent's reference by type casting
System.out.println(((Child) parent).x);// Output - "Child`s Instance Variable"
}
</code></pre>
<br />
In above example when we call overridden method <code>printInstanceVariable()</code> on <code>parent</code> while holding <code>Child</code>'s object in it we can see the output is <code>Child`</code><code>s Instance Variable, Parent`</code><code>s Instance Variable</code> because in child class method is printing <code>Child</code> class's <code>x</code> variable and <code>super.x</code>.<br />
<br />
But when we call <code>System.out.println(parent.variable);</code> on same parent reference which is holding child's object, it prints <code>Parent</code><code>s Instance Variable</code> because <code>new Child()</code> object keeps parent's <code>x</code> as well as child's <code>x</code> and hides parent's <code>x</code>. So, in this case, <code>x</code> is chosen from the class that is the reference type.<br />
<br />
But if we wanted to access child's variable even if we are using parent reference we can do that by using <code>(Child) parent).variable</code>.<br />
<br />
When our variables are private or is in another package and has default access, such variables are not visible outside that class and child class cannot access them. So there no confusion and that is why we should always stick to <a href="https://programmingmitra.com/2016/05/plain-old-java-object-pojo-explained.html" target="_blank">General Guidelines to create POJOs</a> and declare our variables with private access and also provide proper get/set methods to access them.<br />
<br />
Do you want to know more about variable hiding?, In the article <a href="https://programmingmitra.com/2018/11/why-instance-variable-of-super-class-is-not-overridden-In-sub-class.html" target="_blank">Why Instance Variable Of Super Class Is Not Overridden In Sub Class</a>, I have discussed why variables do not follow overriding, why variable hiding is not designed same as method overriding and why instance variable is chosen from reference type instead of the object? Please go ahead and read it.<br />
<br />
You can find complete code on this <a href="https://github.com/njnareshjoshi/exercises/blob/master/src/org/programming/mitra/exercises/VariableShadowingExample.java" target="_blank">Github Repository</a> and please feel free to provide your valuable feedback.<br />
<br /></div>
Naresh Joshihttp://www.blogger.com/profile/01073925481525463593noreply@blogger.com9tag:blogger.com,1999:blog-3832771837877502009.post-40799085494643683322017-12-20T23:53:00.000+05:302019-01-26T13:15:17.477+05:30Why We Should Follow Method Overriding Rules<div dir="ltr" style="text-align: left;" trbidi="on">
In my previous articles <a href="https://programmingmitra.com/2017/12/why-to-follow-method-overloading-rules.html" target="_blank">Why Should We Follow Method Overloading Rules</a>, I discussed about method overloading and rules we need to follow to overload a method. I have also discussed why we need to follow these rules and why some method overloading rules are necessary and others are optional.<br />
<br />
In a similar manner in this article, we will see what rules we need to follow to override a method and why we should follow these rules.<br />
<br />
<h2>
Method Overriding and its Rules</h2>
As discussed in <a href="https://programmingmitra.com/2017/05/everything-about-method-overloading-vs-method-overriding.html" target="_blank">Everything About Method Overloading Vs Method Overriding</a>, every child class inherits all the inheritable behaviour from its parent class but the child class can also define its own new behaviours or override some of the inherited behaviour.<br />
<br />
Overriding means redefining a behaviour (method) again in the child class which was already defined by its parent class but to do so overriding method in the child class must follow certain rules and guidelines.<br />
<br />
With respect to the method it overrides, the overriding method must follow following rules.<br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiS6bmGKPQAcTeRRJip7hp8rcDjchObJcI_kl8lbXguPcEa-JD_wayyBuomwr1duEGfarIAEUmJ3HYUJ9qsCZ_1gnXU8OV1BQwso7HVDdUwBDR_3JLtiXVxrvg6eCxoy5Hwm9eLupnv5O4/s1600/method-overriding-rules.JPG" imageanchor="1"><img alt="Why We Should Follow Method Overriding Rules" border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiS6bmGKPQAcTeRRJip7hp8rcDjchObJcI_kl8lbXguPcEa-JD_wayyBuomwr1duEGfarIAEUmJ3HYUJ9qsCZ_1gnXU8OV1BQwso7HVDdUwBDR_3JLtiXVxrvg6eCxoy5Hwm9eLupnv5O4/s1600/method-overriding-rules.JPG" title="Why We Should Follow Method Overriding Rules" /></a><br />
<br />
To understand these reasons properly let's consider below example where we have a class <code>Mammal</code> which defines <code>readAndGet</code> method which is reading some file and returning an instance of class <code>Mammal</code>.<br />
<br />
Class <code>Human</code> extends class <code>Mammal</code> and overrides <code>readAndGet</code> method to return instance of <code>Human</code> instead of instance of <code>Mammal</code>.<br />
<br />
<pre><code>class Mammal {
public Mammal readAndGet() throws IOException {//read file and return Mammal`s object}
}
class Human extends Mammal {
@Override
public Human readAndGet() throws FileNotFoundException {//read file and return Human object}
}
</code></pre>
<br />
And we know in case of method overriding we can make polymorphic calls. Which means if we assign a child instance to a parent reference and call an overridden method on that reference eventually the method from child class will get called.<br />
<br />
Let's do that<br />
<br />
<pre><code>Mammal mammal = new Human();
try {
Mammal obj = mammal.readAndGet();
} catch (IOException ex) {..}
</code></pre>
<br />
As discussed in <a href="https://programmingmitra.com/2017/05/how-does-jvm-handle-method-overriding-internally.html" target="_blank">How Does JVM Handle Method Overloading and Overriding Internally</a> till compilation phase compiler thinks the method is getting called from the parent class. While bytecode generation phase compiler generates a <code>constant pool</code> where it maps every method string literal and class reference to a memory reference<br />
<br />
During runtime, JVM creates a <code>vtable</code> or <code>virtual table</code> to identify which method is getting called exactly. JVM creates a <code>vtable</code> for every class and it is common for all the objects of that class. Mammal row in a <code>vtable</code> contains method name and memory reference of that method.<br />
<br />
First JVM creates a <code>vtable</code> for the parent class and then copy that parent's <code>vtable</code> to child class's <code>vtable</code> and update just the memory reference for the overloaded method while keeping the same method name.<br />
<br />
You can read it more clearly on <a href="https://programmingmitra.com/2017/05/how-does-jvm-handle-method-overriding-internally.html" target="_blank">How Does JVM Handle Method Overloading and Overriding Internally</a> if it seems hard.<br />
So as of now we are clear that<br />
<ul>
<li>For compiler <code>mammal.readAndGet()</code> means method is getting called from instance of class <code>Mammal</code></li>
<li>For JVM <code>mammal.readAndGet()</code> is getting called from a memory address which <code>vtable</code> is holding for <code>Mammal.readAndGet()</code> which is pointing to a method call from class <code>Human</code>.</li>
</ul>
<h2>
Why overriding method must have same name and same argument list</h2>
Well conceptually <code>mammal</code> is pointing to an object of class <code>Human</code> and we are calling <code>readAndGet</code> method on <code>mammal</code>, so to get this call resolved at runtime <code>Human</code> should also have a method <code>readAndGet</code>. And if <code>Human</code> have inherited that method from <code>Mammal</code> then there is no problem but if <code>Human</code> is overriding <code>readAndGet</code>, it should provide the same method signature as provided by <code>Mammal</code> because method has been already got called according to that method signature.<br />
<br />
But you may be asking how it is handled physically from <code>vtables</code> so I must tell you that, JVM creates a <code>vtable</code> for every class and when it encounters an overriding method it keeps the same method name (<code>Mammal.readAndGet()</code>) while just update the memory address for that method. So both overridden and overriding method must have same method and argument list.<br />
<br />
<h2>
Why overriding method must have same or covariant return type</h2>
So we know, for compiler the method is getting called from class <code>Mammal</code> and for JVM call is from the instance of class <code>Human</code> but in both cases, <code>readAndGet</code> method call must return an object which can be assigned to <code>obj</code>. And since <code>obj</code> is of the type <code>Mammal</code> it can either hold an instance of <code>Mammal</code> class or an instance of a child class of <code>Mammal</code> (child of <code>Mammal</code> are covariant to <code>Mammal</code>).<br />
<br />
Now suppose if <code>readAndGet</code> method in <code>Human</code> class is returning something else so during compile time <code>mammal.readAndGet()</code> will not create any problem but at runtime, this will cause a <code>ClassCastException</code> because at runtime <code>mammal.readAndGet()</code> will get resolved to <code>new Human().readAndGet()</code> and this call will not return an object of type <code>Mammal</code>.<br />
<br />
And this why having a different return type is not allowed by the compiler in the first place.<br />
<br />
<h2>
Why overriding method must not have a more restrictive access modifier</h2>
The same logic is applicable here as well, call to <code>readAndGet</code> method will be resolved at runtime and as we can see <code>readAndGet</code> is public in class <code>Mammal</code>, now suppose<br />
<ul>
<li>If we define <code>readAndGet</code> as <code>default</code> or <code>protected</code> in <code>Human</code> but Human is defined in another package</li>
<li>If we define <code>readAndGet</code> as <code>private</code> in <code>Human</code></li>
</ul>
In both cases code will compile successfully because for compiler <code>readAndGet</code> is getting called from class <code>Mammal</code> but in both cases, JVM will not be able to access <code>readAndGet</code> from <code>Human</code> because it will be restricted.<br />
<br />
So to avoid this uncertainty, assigning restrictive access to the overriding method in the child class is not allowed at all.<br />
<br />
<h2>
Why overriding method may have less restrictive access modifier</h2>
If <code>readAndGet</code> method is accessible from <code>Mammal</code> and we are able to execute <code>mammal.readAndGet()</code> which means this method is accessible. And we make <code>readAndGet</code> less restrictive <code>Human</code> which means it will be more open to get called.<br />
<br />
So making the overriding method less restrictive cannot create any problem in the future and that's it is allowed.<br />
<br />
<h2>
Why overriding method must not throw new or broader checked exceptions</h2>
Because <code>IOException</code> is a checked exception compiler will force us to catch it whenever we call <code>readAndGet</code> on <code>mammal</code><br />
<br />
Now suppose <code>readAndGet</code> in <code>Human</code> is throwing any other checked exception e.g. <code>Exception</code> and we know <code>readAndGet</code> will get called from the instance of <code>Human</code> because <code>mammal</code> is holding <code>new Human()</code>.<br />
<br />
Because for compiler the method is getting called from <code>Mammal</code>, so the compiler will force us to handle only <code>IOException</code> but at runtime we know method will be throwing <code>Exception</code> which is not getting handled and our code will break if the method throws an exception.<br />
<br />
That's why it is prevented at the compiler level itself and we are not allowed to throw any new or broader checked exception because it will not be handled by JVM at the end.<br />
<br />
<h2>
Why overriding method may throw narrower checked exceptions or any unchecked exception</h2>
But if <code>readAndGet</code> in <code>Human</code> throws any sub-exception of <code>IOException</code> e.g., <code>FileNotFoundException</code>, it will be handled because <code>catch (IOException ex)</code> can handle all child of <code>IOException</code>.<br />
<br />
And we know unchecked exception (subclasses of <code>RuntimeException</code>) are called unchecked because we don't need to handle them necessarily.<br />
<br />
And that's why overriding methods are allowed to throw narrower checked and other unchecked exceptions.<br />
<br />
To force our code to adhere method overriding rules we should always use <code>@Override</code> annotation on our overriding methods, <code>@Override</code> annotation force compiler to check if the method is a valid override or not.<br />
<br />
You can find complete code on this <a href="https://github.com/njnareshjoshi/exercises/blob/master/src/org/programming/mitra/exercises/OverridingInternalExample.java" target="_blank">Github Repository</a> and please feel free to provide your valuable feedback.</div>
Naresh Joshihttp://www.blogger.com/profile/01073925481525463593noreply@blogger.com3tag:blogger.com,1999:blog-3832771837877502009.post-5484920111527570522017-12-16T22:50:00.000+05:302019-01-26T13:20:06.919+05:30Why Should We Follow Method Overloading Rules<div dir="ltr" style="text-align: left;" trbidi="on">
In my previous articles, <a href="https://programmingmitra.com/2017/05/everything-about-method-overloading-vs-method-overriding.html" target="_blank">Everything About Method Overloading Vs Method Overriding</a> and <a href="https://programmingmitra.com/2017/05/how-does-jvm-handle-method-overriding-internally.html" target="_blank">How Does JVM Handle Method Overloading and Overriding Internally</a>, I have discussed what is method overloading and overriding, how both are different than each other, How JVM handles them internally and what rules we should follow in order to implement these concepts.<br />
<br />
In order to overload or override a method we need to follow certain rules, some of them are mandatory while others are optional and to become a good programmer we should always try to understand the reason behind these rules.<br />
<br />
I am going to write two articles where I will try to look into the method overloading and overriding rules and try to figure out why we need to follow them.<br />
<br />
In this article, we will see what rules we should follow to overload a method and we will also try to know why we should follow these rules.<br />
<br />
<h1>
Method Overloading</h1>
In general, method overloading means reusing same method name to define more than one method but all methods must have a different argument list.<br />
<br />
We can take the example of the <code>print</code> method present in <code>PrintStream</code> class which gets called when we call <code>System.out.print()</code> to print something. By calling this method on several data types it seems like there is just one <code>print</code> method which is accepting all types and printing their values.<br />
<br />
But actually, there are 9 different <code>print</code> methods as shown in below image<br />
<br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgC_etUGK0nH3Y2fzs2tae-q8Yj8MvYdvEch7O26UCk9TebNeNGZ4VRiTbMUNVcDwElPe6dAGY4nK7tbD_rbAtZ9kIicqEbpoaXeYOOSn_Ch53J9ZWJKVs3dr5zazZfyoGYiX4DK-25K-M/s1600/method-overloading.PNG"><img alt="method-overloading" border="0" height="232" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgC_etUGK0nH3Y2fzs2tae-q8Yj8MvYdvEch7O26UCk9TebNeNGZ4VRiTbMUNVcDwElPe6dAGY4nK7tbD_rbAtZ9kIicqEbpoaXeYOOSn_Ch53J9ZWJKVs3dr5zazZfyoGYiX4DK-25K-M/s640/method-overloading.PNG" title="method-overloading" width="640" /></a><br />
<br />
Well, the <code>PrintStream</code> class creator could have created methods like <code>printBoolean</code> or <code>printInt</code> or <code>printFloat</code>, but the idea behind naming all the 9 methods same is to let the user think that there is only one method which is printing whatever we pass to it.<br />
<br />
Which sounds like polymorphism but as discussed in the article <a href="https://programmingmitra.com/2017/05/how-does-jvm-handle-method-overriding-internally.html" target="_blank">How Does JVM Handle Method Overloading and Overriding Internally</a> that how method overloading get resolved at compile time, some people also term method overloading as <b>compile-time polymorphism</b>.<br />
<br />
<h1>
Method Overloading Rules</h1>
<div>
While defining a method we need to provide it with a proper method signature which includes<b> access specifier, return type, method name, argument list, exceptions method might throw. </b>Based on these five things method overloading has some mandatory rules and some optional rules, which we are going to see below.<br />
<br /></div>
<h3 style="text-align: left;">
Mandatory Rules</h3>
<ul>
<li><strong>Overloaded methods must have same method name:</strong> Having the same name let us reuse the same method name for different purposes and let the user believe that there is only one method which is accepting different kinds of input and doing the work according to the input.</li>
</ul>
<ul>
<li><strong>Overloaded methods must have different argument lists:</strong> Since all overloaded methods must have the same name, having a different argument list becomes necessary because it is the only way to differentiate the methods from each other. Java compiler differentiates a method from other based on its method name and argument list, So different argument list helps the compiler to differentiate and recognize methods from each other so the compiler will know which method is getting called at compile time only.</li>
</ul>
<div>
<h3>
Optional Rules</h3>
</div>
The compiler knows that at the time of method calling JVM needs to know the method name and JVM will pass some arguments to that method so it must also know the argument list. While other method signature elements e.g. return type, access modifier, the exception method throwing also matter but at the time of method call they become optional.<br />
<br />
So the different argument list is sufficient for the compiler to differentiate between the methods even if they have the same name so the rules mentioned below are optional and we are free to follow or not follow them. Going with below rules totally depends on your requirements and they are there to just provide us with additional functionality.<br />
<ul>
<li><strong>Overloaded methods can have different return types:</strong> Return type matters when the method call is finished and JVM assigning back the value returned by that method call to some variable. But it is not required while calling the method and JVM cannot use it to differentiate between methods based on just return type. So we can either return the same as the overloaded method did or return something different or return nothing.</li>
</ul>
<ul>
<li><strong>Overloaded methods can have different access modifiers: </strong>If a method is getting called by the JVM it means it has passed the compilation phase because executing the bytecode which is already compiled. So access specifier of a method is useful for the compiler but it is useless for JVM and JVM cannot differentiate between methods based on access modifier. So an overloading method can have any access modifier and we can use it according to our need.</li>
</ul>
<ul>
<li><strong>Overloaded methods can throw different checked or unchecked exceptions:</strong> Again what exceptions a method might throw cannot differentiate a method from another method. And also overloaded methods are different from each other but usually, they perform the same operation on different data set and in order to do so overloaded methods may do some different operation as well which may throw a different exception.</li>
</ul>
You can find complete code on this <a href="https://github.com/njnareshjoshi/exercises/blob/master/src/org/programming/mitra/exercises/OverloadingOverridingExample.java" target="_blank">Github Repository</a> and please feel free to provide your valuable feedback.</div>
Naresh Joshihttp://www.blogger.com/profile/01073925481525463593noreply@blogger.com0tag:blogger.com,1999:blog-3832771837877502009.post-58759324708080137292017-05-30T19:04:00.000+05:302019-01-26T13:22:32.420+05:30Everything About Method Overloading Vs Method Overriding<div dir="ltr" style="text-align: left;" trbidi="on">
In a previous article <a href="https://programmingmitra.com/2017/04/Difference-Between-ClassNotFoundException-and-NoClassDefFoundError.html" target="_blank">Everything About ClassNotFoundException Vs NoClassDefFoundError</a>, I have explained ClassNotFoundException and NoClassDefFoundError in details and also discussed their differences and how to avoid them. If you have not read it, please go ahead and give it a look.<br />
<br />
Similar to that here in this article, we will look into one more core concept of Java which is method overloading and overriding. As soon as we start learning Java we get introduced to them and their contracts which are pretty simple to understand but sometimes programmers get confused between them or they do not know either it is a correct overload/override because of the different rules.<br />
<br />
Here we will discuss What is method overloading and overriding, What contract one must follow to correctly overload or override a method, What are the different rules of method overloading and overriding and what are the differences between them.<br />
<br />
<h2 id="method-overloading">
Method Overloading</h2>
Method overloading means providing two separate methods in a class with the same name but different arguments while method return type may or may not be different which allows us to reuse the same method name.<br />
<br />
And this becomes very handy for the consumer of our class, he can pass different types of parameters to the same method (in his eyes but actually they are different) and get the response according to his input e.g. <span style="background-color: #f3f3f3;">System.out.println()</span> method accepts all types of objects primitive types and print them but in reality there several println present in the <span style="background-color: #f3f3f3;">PrintStream</span> class.<br />
<br />
<pre><code>public class PrintStream {
// other methods
public void println() { /*code*/ }
public void println(boolean x) { /*code*/ }
public void println(char x) { /*code*/ }
public void println(int x) { /*code*/ }
public void println(long x) { /*code*/ }
public void println(float x) { /*code*/ }
public void println(double x) { /*code*/ }
public void println(char x[]) { /*code*/ }
public void println(String x) { /*code*/ }
public void println(Object x) { /*code*/ }
// other methods
}</code></pre>
<br />
<blockquote class="tr_bq">
While overloading has nothing to deal with polymorphism but Java programmers also refer method overloading as <strong> Compile Time </strong><strong>Polymorphism</strong><strong> </strong>because which method is going to get called will be decided at compile time only.</blockquote>
<br />
In the case of method overloading compiler decides which method is going to get called based on the reference on which it is getting called and the method name, return type, and argument list.<br />
<br />
<pre><code>class Human {
public String speak() { return "Hello"; }
// Valid overload of speak
public String </code>speak(String language) {
if (language.equals("Hindi")) return "Namaste";
else return "Hello";
}
public long calculate(int a, long b) { return a + b; }
// However nobody should do it but Valid overload of calculate
// by just changing sequence of arguments
public long calculate(long b, int a) { return a + b; }
}
</pre>
<h3 id="method-overloading-rules">
Method Overloading Rules</h3>
There are some rules which we need to follow to overload a method and some of them are mandatory while some are optional.<br />
<br />
Two methods will be treated as Overloaded if both follow below mandatory rule.<br />
<ul>
<li>Both must have same method name</li>
<li>Both must have different argument lists</li>
</ul>
And if both methods follow above mandatory rules then they may or may not<br />
<ul>
<li>Have different return types</li>
<li>Have different access modifiers</li>
<li>Throw different checked or unchecked exceptions</li>
</ul>
Usually, method overloading happens inside a single class but a method can also be treated as overloaded in the subclass of that class because subclass inherits one version of the method from the parent class and then can have another overloaded version in its class definition.<br />
<h2 id="method-overriding">
Method Overriding</h2>
Method Overriding means defining a method in the child class which is already defined in the parent class with same method signature i.e same name, arguments and return type (after Java 5 you can also use a covariant type as return type).<br />
<br />
Whenever we extend a superclass in a child class, child class automatically gets all the methods defined in the super and we call them derived methods. But in some cases we do not want some derived methods to work in a manner which they are doing in the parent then we can override those methods in child class e.g. we always override<code> equals,</code> <code>hashCode
</code> and <code>
toString
</code> from <code>
Object
</code> class, you can read more on <a href="https://programmingmitra.com/2016/11/Java-Cloning-Types-of-Cloning-Shallow-Deep-in-Details-with-Example.html" target="_blank">Why can't we override clone() method from Object class</a>.<br />
<br />
In case of abstract methods either from a parent abstract class or interface we do not have any option we need to implement or in other words override all the abstract methods.<br />
<br />
<blockquote class="tr_bq">
Method overriding is also known as <strong> Runtime Polymorphism </strong> and <strong> Dynamic Method Dispatch </strong> because which method is going to get called is decided at runtime by JVM.</blockquote>
<br />
<pre><code>abstract class Mammal {
// Well might speak something
public String speak() { return "ohlllalalalalalaoaoaoa"; }
}
class Cat extends Mammal {
@Override
public String speak() { return "Meow"; }
}
class Human extends Mammal {
@Override
public String speak() { return "Hello"; }
}
</code></pre>
<br />
<blockquote class="tr_bq">
Using <code>
@Override
</code> annotation on the overridden methods is not necessary but using it will tell you if you are not obeying overriding rules. </blockquote>
<br />
<pre><code>Mammal mammal = new Cat();
System.out.println(mammal.speak()); // Will print Meow
</code></pre>
<br />
At the line <code>
mammal.speak()
</code> compiler says the <code>
speak()
</code> method of reference type <code>
Mammal
</code> is getting called, so for compiler this call is <code>
Mammal.speak()</code>.<br />
<br />
But at the execution time JVM knows clearly that <code>
mammal
</code> reference is holding the reference of object of <code>
Cat</code>, so for JVM this call is <code>
Cat.speak()</code>. You can read more on <a href="https://programmingmitra.com/2017/05/how-does-jvm-handle-method-overriding-internally.html" target="_blank">How Does JVM Handle Method Overloading and Overriding Internally</a>.<br />
<h3 id="method-overriding-rules">
Method Overriding Rules</h3>
Similar to method overloading we also have some mandatory and some optional rules which we need to follow to override a method.<br />
<br />
With respect to the method it overrides, the overriding method must follow below mandatory rule.<br />
<ul>
<li>It must have same method name</li>
<li>Must have same arguments.</li>
<li>Must have the same return type, from Java 5 the return type can also be a subclass (Subclass is a covariant type to its parent).</li>
<li>Must not have a more restrictive access modifier (if parent --> protected then child --> private is not allowed).</li>
<li>Must not throw new or broader checked exceptions.</li>
</ul>
And if both overriding methods follow above mandatory rules then it<br />
<ul>
<li>May have a less restrictive access modifier (if parent --> protected then child --> public is allowed).</li>
<li>May throw fewer or narrower checked exceptions or any unchecked exception.</li>
</ul>
Apart from above rules, there are also some facts<br />
<ul>
<li>Only inherited methods can be overridden, Means methods can be <span style="background-color: #f5f6f5;">overridden</span> in child class only.</li>
<li>Constructors and private methods are not inherited so cannot be overridden.</li>
<li>Abstract methods must be overridden by the first concrete (non-abstract) subclass.</li>
<li>final methods cannot be overridden.</li>
<li>A subclass can use super.overridden_method() to call the superclass version of an overridden method.</li>
</ul>
<h2 id="difference-between-method-overloading-and-method-overriding">
Difference Between Method Overloading and Method Overriding</h2>
<div>
<br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjp1C3LNelq3foTkiX5TNPTd5ZtzLJj0hRqdAbjK78hNKZTweX6QGJutedkqKPaQGlbZnBIQtmfOSdaUVIjKWv2L1a_XxFIrSS2xXf8HRYTzBkVJUpR8GwtWAJUNsl-Rns1WAhQ43CsjDU/s1600/difference-between-method-overloading-and-method-overriding.png" imageanchor="1"><img alt="difference-between-method-overloading-and-method-overriding" border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjp1C3LNelq3foTkiX5TNPTd5ZtzLJj0hRqdAbjK78hNKZTweX6QGJutedkqKPaQGlbZnBIQtmfOSdaUVIjKWv2L1a_XxFIrSS2xXf8HRYTzBkVJUpR8GwtWAJUNsl-Rns1WAhQ43CsjDU/s1600/difference-between-method-overloading-and-method-overriding.png" title="difference-between-method-overloading-and-method-overriding" /></a><br />
<br />
You can find complete code on this <a href="https://github.com/njnareshjoshi/exercises/blob/master/src/org/programming/mitra/exercises/OverloadingOverridingExample.java" target="_blank">Github Repository</a> and please feel free to provide your valuable feedback.</div>
</div>
Naresh Joshihttp://www.blogger.com/profile/01073925481525463593noreply@blogger.com3tag:blogger.com,1999:blog-3832771837877502009.post-4869828763452140912017-05-30T18:57:00.002+05:302020-07-03T00:44:57.844+05:30How Does JVM Handle Polymorphism (Method Overloading and Method Overriding) Internally<div dir="ltr" style="text-align: left;" trbidi="on">
In my previous article <a href="https://programmingmitra.com/2017/05/everything-about-method-overloading-vs-method-overriding.html" target="_blank"> Everything About Method Overloading Vs Method Overriding</a>, I have discussed method overloading and overriding, their rules and differences.<br />
<br />
In this article, we will see How Does JVM Handle Method Overloading And Overriding Internally, how JVM identifies which method should get called.<br />
<br />
Let’s take the example of a parent class<code> Mammal
</code> and a child<code> Human
</code> classes from our previous blog to understand it more clearly.<br />
<br />
<pre><code>public class OverridingInternalExample {
private static class Mammal {
public void speak() { System.out.println("ohlllalalalalalaoaoaoa"); }
}
private static class Human extends Mammal {
@Override
public void speak() { System.out.println("Hello"); }
// Valid overload of speak
public void speak(String language) {
if (language.equals("Hindi")) System.out.println("Namaste");
else System.out.println("Hello");
}
@Override
public String toString() { return "Human Class"; }
}
// Code below contains the output and and bytecode of the method calls
public static void main(String[] args) {
Mammal anyMammal = new Mammal();
anyMammal.speak(); // Output - ohlllalalalalalaoaoaoa
// 10: invokevirtual #4 // Method org/programming/mitra/exercises/OverridingInternalExample$Mammal.speak:()V
Mammal humanMammal = new Human();
humanMammal.speak(); // Output - Hello
// 23: invokevirtual #4 // Method org/programming/mitra/exercises/OverridingInternalExample$Mammal.speak:()V
Human human = new Human();
human.speak(); // Output - Hello
// 36: invokevirtual #7 // Method org/programming/mitra/exercises/OverridingInternalExample$Human.speak:()V
human.speak("Hindi"); // Output - Namaste
// 42: invokevirtual #9 // Method org/programming/mitra/exercises/OverridingInternalExample$Human.speak:(Ljava/lang/String;)V
}
}
</code></pre>
<br />
We can answer this answer in two ways, Logical way and Physical way, let's take a look at the logical way.<br />
<br />
<h2 id="logical-way">
Logical Way</h2>
Logically we can say, during compilation phase calling method is considered from the reference type. But at execution time method will be called from the object which the reference is holding.<br />
<br />
For Example on <code>
humanMammal.speak();
</code> line compiler will say <code>
Mammal.speak()
</code> is getting called because <code>
humanMammal
</code> is of type <code>
Mammal
</code> . But during execution, JVM knows that <code>
humanMammal
</code> is holding a <code>
Human's
</code> object so <code>
Human.speak()
</code> will get called.<br />
<br />
Well, it is pretty simple until we keep it at the conceptual level only. Once we get the doubt that how JVM is handling all this internally? or how JVM is calculating which method it should call.<br />
<br />
Also, we know that overloaded methods are not called polymorphic and get resolved at compile time and this is why sometimes method overloading is also known as<strong> compile time polymorphism or early/static binding</strong>.<br />
<br />
But overridden methods get resolved at runtime time because the compiler does not know that, the object which we are assigning to our reference have overridden the method or not.<br />
<br />
<h2 id="physical-way">
Physical Way</h2>
In this section, we will try to find out physical proof of all aforementioned statements and to find them we will read the bytecode of our program which we can do by executing <code>
javap -verbose OverridingInternalExample</code>. By using <code>
-verbose
</code> option we will get the descriptive bytecode same as our Java program.<br />
<br />
Above command shows the bytecode in two sections<br />
<br />
<strong> 1. Constant Pool: </strong> holds almost everything which is necessary for our program’s execution e.g. method references (<code>#Methodref</code>), Class objects ( <code>
#Class
</code> ), string literals ( <code>
#String
</code> ), please click one image to zoom.<br />
<br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg2DXu2gjXzYso8TR_7o5gFm0pi1-xnAEAVO2OpihvE9VnC_t7nnG80L40d1oWAOEKTHFqlQsNeoUzJ8Cln8Vo3XV-5aTZqjFOoAXlR2Sc5rL3s2BC6znNC5P42CXuUYdCCYovW-9Mb8GA/s1600/java-constant-pool-method-table.png"><img alt="java-method-area-or-constant-pool-or-method-table" border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg2DXu2gjXzYso8TR_7o5gFm0pi1-xnAEAVO2OpihvE9VnC_t7nnG80L40d1oWAOEKTHFqlQsNeoUzJ8Cln8Vo3XV-5aTZqjFOoAXlR2Sc5rL3s2BC6znNC5P42CXuUYdCCYovW-9Mb8GA/s1600/java-constant-pool-method-table.png" title="java-method-area-or-constant-pool-or-method-table" /></a><br />
<br />
<br />
<strong> 2. Program’s Bytecode</strong>: executable bytecode instructions, please click one image to zoom.<br />
<br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEikssXicAHSBEa4280nv0WaAKzCv3z73ec7pj8guaiYAAFx7QCjVn_fEdpPU7h5ifOJSgvudfjLpN4SfQq0wY3T08eu58JOW6X9vXlZ2E6Lz96huDux-SOTDrX6WATk6GbW7GaXte8G-co/s1600/method-overloading-overriding-internals-byte-code.png"><img alt="method-overloading-overriding-internals-byte-code" border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEikssXicAHSBEa4280nv0WaAKzCv3z73ec7pj8guaiYAAFx7QCjVn_fEdpPU7h5ifOJSgvudfjLpN4SfQq0wY3T08eu58JOW6X9vXlZ2E6Lz96huDux-SOTDrX6WATk6GbW7GaXte8G-co/s1600/method-overloading-overriding-internals-byte-code.png" title="method-overloading-overriding-internals-byte-code" /></a><br />
<br />
<h2 id="why-method-overloading-is-called-static-binding">
Why Method overloading is called static binding</h2>
In the above mention code <code>
humanMammal.speak()
</code> compiler will say <code>
speak()
</code> is getting called from <code>
Mammal
</code> but at execution time it will be called from the object which <code>
humanMammal
</code> is holding, which is the object of the<code> Human
</code> class.<br />
<br />
And by looking at the above code and images we can see that the bytecodes of <code>
humanMammal.speak()
</code> , <code>
human.speak()
</code> and <code>
human.speak("Hindi")
</code> are totally different because the compiler is able to differentiate between them based on the class reference.<br />
<br />
So in the case of method overloading compiler is able to identify the bytecode instructions and method’s address at compile time and that is why it is also known as<strong> static binding or compile time polymorphism</strong>.<br />
<br />
<h2 id="why-method-overriding-is-called-dynamic-binding">
Why Method overriding is called dynamic binding</h2>
Bytecode for <code>
anyMammal.speak()
</code> and <code>
humanMammal.speak()
</code> are same ( <code>
invokevirtual #4 // Method org/programming/mitra/exercises/OverridingInternalExample$Mammal.speak:()V
</code> ) because according to compiler both methods are called on <code>
Mammal
</code> reference.<br />
<br />
So now the question comes if both method calls have same bytecode then how does JVM know which method to call?<br />
<br />
Well, the answer is hidden in the bytecode itself and it is <code>
invokevirtual
</code> instruction, according to JVM specification<br />
<br />
<blockquote>
invokevirtual invokes an instance method of an object, dispatching on the (virtual) type of the object. This is the normal method dispatch in the Java programming language.
</blockquote>
<br />
JVM uses the <code>
invokevirtual
</code> instruction to invoke Java equivalent of the C++ virtual methods. In C++ if we want to override one method in another class we need to declare it as <code>
virtual</code>, But in Java, all methods are virtual by default (<span style="background-color: white;">except final and static methods</span>) because we can override every method in the child class.<br />
<br />
Operation <code>
invokevirtual
</code> accepts a pointer to method reference call ( <code>
#4
</code> an index into the constant pool)<br />
<br />
<pre><code>invokevirtual #4 // Method org/programming/mitra/exercises/OverridingInternalExample$Mammal.speak:()V
</code></pre>
<br />
And that method reference <span style="font-family: monospace;">#4</span> again refers to a method name and Class reference<br />
<br />
<pre><code>#4 = Methodref #2.#27 // org/programming/mitra/exercises/OverridingInternalExample$Mammal.speak:()V
#2 = Class #25 // org/programming/mitra/exercises/OverridingInternalExample$Mammal
#25 = Utf8 org/programming/mitra/exercises/OverridingInternalExample$Mammal
#27 = NameAndType #35:#17 // speak:()V
#35 = Utf8 speak
#17 = Utf8</code> ()V</pre>
<br />
All these references combinedly used to get a reference to a method and class in which the method is to be found. This is also mentioned in JVM Specification<br />
<br />
<blockquote>
The Java virtual machine does not mandate any particular internal structure for objects 4.
</blockquote>
<br />
And the bookmark 4 states<br />
<br />
<blockquote>
In some of Oracle’s implementations of the Java virtual machine, a reference to a class instance is a pointer to a handle that is itself a pair of pointers: one to a table containing the methods of the object and a pointer to the Class object that represents the type of the object, and the other to the memory allocated from the heap for the object data.
</blockquote>
<br />
It means every reference variable holds two hidden pointers<br />
<ol>
<li>A pointer to a table which again holds methods of the object and a pointer to the Class object. e.g. [speak(), speak(String) Class object]</li>
<li>A pointer to the memory allocated on the heap for that object’s data e.g. values of instance variables.</li>
</ol>
But again the question comes, how <code>
invokevirtual
</code> internally do this? Well, no one can answer this because it depends on JVM implementation and it varies from JVM to JVM.<br />
<br />
And from the above statements, we can conclude that an object reference indirectly holds a reference/pointer to a table which holds all the method references of that object. Java has borrowed this concept from C++ and this table is known by various names which such as <a href="https://en.wikipedia.org/wiki/Virtual_method_table" target="_blank">virtual method table ( <strong> VMT </strong> ), virtual function table (<strong>vftable</strong>), virtual table (<strong>vtable</strong>), dispatch table</a>.<br />
<br />
We can not sure of how <code>
vtable
</code> is implemented in Java because it is JVM dependent. But we can expect that it will be following the same strategy as C++ where <code>
vtable
</code> is an array like structure which holds method names and their references on array indices. And whenever JVM tries to execute a virtual method it always asks the <code>
vtable
</code> for it address.<br />
<br />
There is only one <code>
vtable
</code> per class, which means it is unique and same for all objects of a class similar to <code>Class </code>object. I have discussed more on <code>
Class
</code> object in my articles <a href="https://programmingmitra.com/2016/10/why-outer-java-class-cant-be-static.html" target="_blank"> Why an outer Java class can’t be static</a> and <a href="https://programmingmitra.com/2016/06/why-java-is-purely-object-oriented-or-why-not.html" target="_blank"> Why Java is Purely Object-Oriented Language Or Why Not</a>.<br />
<br />
So there is only one <code>
vtable
</code> for <code>
Object </code>class which contains all 11 methods (if we don't count registerNatives) and references to their respective method bodies.<br />
<br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhCrH_xF9u6CuY7cme2FX2JFQyMeJzfh1pI1r9u57viztUFiObmCvbErcBgmdzoLX37B5Czp7-4CM9e-DyeW4sqWI85V2fOukok0pJa9TPP_AhyQLDUSp9szY9rPjziniRYz9QhSU7qUHc/s1600/vtable-of-object.png"><img alt="vtable-of-object" border="0" height="220" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhCrH_xF9u6CuY7cme2FX2JFQyMeJzfh1pI1r9u57viztUFiObmCvbErcBgmdzoLX37B5Czp7-4CM9e-DyeW4sqWI85V2fOukok0pJa9TPP_AhyQLDUSp9szY9rPjziniRYz9QhSU7qUHc/s640/vtable-of-object.png" title="vtable-of-object" width="640" /></a><br />
<br />
When JVM loads the <code>
Mammal
</code> class into memory it creates a <code>
Class
</code> object for it and creates a <code>
vtable
</code> which contains all the methods from the vtable of Object class with the same references (Because <code>
Mammal
</code> is not overriding any method from Object) and adds a new entry for <code>
speak
</code> method.<br />
<br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjXGZ-lFty-l9HTMcQGJRFgBofUIPEsFMmjDRW1ttp1UANhUymWcXU5nPgDV6mjsjDRWD-z4365jKp2OKjVnAZKhlFYgRLWyEop01ZNcrLhf6iVf1sgmCMKpZrhRQ4JuU8cs7TQCiKxuvs/s1600/vtable-of-mammal.png"><img alt="vtable-human" border="0" height="185" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjXGZ-lFty-l9HTMcQGJRFgBofUIPEsFMmjDRW1ttp1UANhUymWcXU5nPgDV6mjsjDRWD-z4365jKp2OKjVnAZKhlFYgRLWyEop01ZNcrLhf6iVf1sgmCMKpZrhRQ4JuU8cs7TQCiKxuvs/s640/vtable-of-mammal.png" title="vtable-human" width="640" /></a><br />
<br />
<br />
Now here comes the turn of <code>
Human
</code> class and now JVM will copy all entries from the <code>
vtable
</code> of <code>
Mammal
</code> class to the <code>
vtable
</code> of <code>
Human
</code> and adds a new entry for the overloaded version of <code>
speak(String)</code>.<br />
<br />
JVM knows that <code>
Human
</code> class has overridden two methods one is <code>
toString()
</code> from <code>
Object
</code> and second is <code>
speck()
</code> from <code>
Mammal
</code> . Now instead of creating new entries for these methods with updated references. JVM will modify the references to the already present methods on the same index where they were present earlier and will keep the same method names.<br />
<br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjxqT5RZ5JdNqGI5kdPq4JayRGh5Z0cxIiHf7gFlps9m4mJJiIPEtPh_36jYI9lD1E5DfB0jqEi1U4SPHiYMnZ6yaXHWyhj6ihhn0ypiFWL0z9Ekuf9iHXoiJ_8ZUUaMDtYYp9EVmSjI4M/s1600/vtable-of-human.png"><img border="0" height="224" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjxqT5RZ5JdNqGI5kdPq4JayRGh5Z0cxIiHf7gFlps9m4mJJiIPEtPh_36jYI9lD1E5DfB0jqEi1U4SPHiYMnZ6yaXHWyhj6ihhn0ypiFWL0z9Ekuf9iHXoiJ_8ZUUaMDtYYp9EVmSjI4M/s640/vtable-of-human.png" width="640" /></a><br />
<br />
<br />
The <code>
invokevirtual
</code> causes the JVM to treat the value at method reference <code>
#4
</code> , not as an address but as the name of a method to look up in the <code>
vtable
</code> for the current object.<br />
<br />
I hope now it would have become a little bit clear that how the JVM mixes <code>
constant pool
</code> entries and <code>
vtable
</code> to conclude which method it is going to call.<br />
<br />
You can find the complete code on this <a href="https://github.com/njnareshjoshi/exercises/blob/master/src/org/programming/mitra/exercises/OverridingInternalExample.java" target="_blank">Github Repository</a> and please feel free to provide your valuable feedback.</div>
Naresh Joshihttp://www.blogger.com/profile/01073925481525463593noreply@blogger.com36tag:blogger.com,1999:blog-3832771837877502009.post-57446194898782604542017-04-08T14:49:00.001+05:302018-10-23T18:32:46.994+05:30Everything About ClassNotFoundException Vs NoClassDefFoundError<div dir="ltr" style="text-align: left;" trbidi="on">
We know Java is an Object Oriented Programming Language and almost everything is an object in Java and in order to create an object we need a class.<br />
<br />
While executing our program whenever JVM find a class, First JVM will try to load that class into memory if it has not done it already.<br />
<br />
For Example, If JVM is executing below the line of code, before creating the object of Employee class JVM will load this class into memory using a ClassLoader.<br />
<br />
<pre><code>Employee emp = new Employee();
</code></pre>
<br />
In above example, JVM will load the Employee class because it is present in the execution path and JVM want to create an object of this class.<br />
<br />
But we can also ask JVM to just load a class through its string name using Class.forName() or ClassLoader.findSystemClass() or ClassLoader.loadClass() methods. For Example below the line of code will only load the Employee class into memory and do nothing else.<br />
<br />
<pre><code>Class.forName("Employee");
</code></pre>
<br />
Both <strong> ClassNotFoundException </strong>and <strong>NoClassDefFoundError </strong> occur when a particular class is not found at run time but under different scenarios. And here in this article, we going to study these different scenarios.<br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<h3 id="classnotfoundexception">
</h3>
<h3 id="classnotfoundexception">
ClassNotFoundException</h3>
Is a checked exception that occurs when we tell JVM to load a class by its string name using<code><span style="background-color: #eeeeee;">
Class.forName()</span>
</code>or <code><span style="background-color: #eeeeee;">
ClassLoader.findSystemClass()</span>
</code> or <code><span style="background-color: #eeeeee;">ClassLoader.loadClass() </span></code><span style="background-color: #f5f6f5;">methods </span>and mentioned class is not found in the classpath.<br />
<br />
Most of the time, this exception occurs when you try to run an application without updating the classpath with required JAR files. For Example, You may have seen this exception when doing the JDBC code to connect to your database i.e.MySQL but your classpath does not have JAR for it.<br />
<br />
If we compile below example, the compiler will produce two class files <code><span style="background-color: #eeeeee;">Test.class</span>
</code> and <code><span style="background-color: #eeeeee;">
Person.class</span></code>. And Now if we execute the program it will successfully print <code style="background-color: #eeeeee;">
Hello</code>. But if we delete Person.class file and again try to execute the program we will receive ClassNotFoundException.<br />
<br />
<pre><code>public class Test {
public static void main(String[] args) throws Exception {
// ClassNotFoundException Example
// Provide any class name to Class.forName() which does not exist
// Or compile Test.java and then manually delete Person.class file so Person class will become unavailable
// Run the program using java Test
Class clazz = Class.forName("Person");
Person person = (Person) clazz.newInstance();
person.saySomething();
}
}
class Person {
void saySomething() {
System.out.println("Hello");
}
}
</code></pre>
<h3 id="noclassdeffounderror">
</h3>
<h3 id="noclassdeffounderror">
NoClassDefFoundError</h3>
Is a subtype of <code><span style="background-color: #eeeeee;">
java.lang.Error</span>
</code> and <code><span style="background-color: #eeeeee;">
Error</span>
</code> class indicates an abnormal behavior which really should not happen with an application but and application developers should not try to catch it, it is there for JVM use only.<br />
<br />
NoClassDefFoundError occurs when JVM tries to load a particular class that is the part of your code execution (as part of a normal method call or as part of creating an instance using the <code>
new
</code> keyword) and that class is not present in your classpath but was present at compile time because in order to execute your program you need to compile it and if you are trying use a class which is not present compiler will raise compilation error.<br />
<br />
Similar to above example if we try to compile below program, we will get two class files <code><span style="background-color: #eeeeee;">
Test.class</span>
</code> and <code><span style="background-color: #eeeeee;">
Employee.class.</span> A</code> and on execution it will print <code><span style="background-color: #eeeeee;">
Hello</span></code>.<br />
<br />
<pre><code>public class Test {
public static void main(String[] args) throws Exception {
// NoClassDefFoundError Example
// Do javac on Test.java,
// Program will compile successfully because Empoyee class exits
// Manually delete Employee.class file
// Run the program using java Test
Employee emp = new Employee();
emp.saySomething();
}
}
class Employee {
void saySomething() {
System.out.println("Hello");
}
}
</code></pre>
<br />
But if we delete <span style="background-color: #eeeeee;">Employee.class</span> and try to execute the program we will get NoClassDefFoundError.<br />
<br />
<pre><code>Exception in thread "main" java.lang.NoClassDefFoundError: Employee
at Test.main(Test.java:9)
Caused by: java.lang.ClassNotFoundException: Employee
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 1 more
</code></pre>
<br />
As you can see in above stack trace NoClassDefFoundError is caused by ClassNotFoundException, because JVM is not able to find the <span style="background-color: #eeeeee;">Employee</span> class in the class path.<br />
<h3 id="noclassdeffounderror">
Conclusion</h3>
<div>
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgeznvVLK1qaZqJ-ZLzUTln8Lo9n5TDLWqiJclEk1lgoXxu-xEmv57KieZqbwVgCAu7pyGHYAJJA8UkBtjUnOyQqnAFjg6TWXCXsGn7LeyfAOdQXwjeY0E7ITXXfJHFsXHNH5f34zOaXA8/s1600/Difference-Between-ClassNotFoundException-and-NoClassDefFoundError.png"><img alt="Difference-Between-ClassNotFoundException-and-NoClassDefFoundError" border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgeznvVLK1qaZqJ-ZLzUTln8Lo9n5TDLWqiJclEk1lgoXxu-xEmv57KieZqbwVgCAu7pyGHYAJJA8UkBtjUnOyQqnAFjg6TWXCXsGn7LeyfAOdQXwjeY0E7ITXXfJHFsXHNH5f34zOaXA8/s1600/Difference-Between-ClassNotFoundException-and-NoClassDefFoundError.png" title="Difference-Between-ClassNotFoundException-and-NoClassDefFoundError" /></a><br />
<br />
You can find complete code on this <a href="https://github.com/njnareshjoshi/exercises/blob/master/src/org/programming/mitra/exercises/ClassNotFoundExceptionExample.java" target="_blank">Github Repository</a> and please feel free to provide your valuable feedback.</div>
</div>
Naresh Joshihttp://www.blogger.com/profile/01073925481525463593noreply@blogger.com4tag:blogger.com,1999:blog-3832771837877502009.post-42379306663650996612017-03-02T23:19:00.001+05:302020-07-03T00:48:08.036+05:30AutoWiring Spring Beans Into Classes Not Managed By Spring Like JPA Entity Listeners<div dir="ltr" style="text-align: left;" trbidi="on">
In my previous article <a href="https://programmingmitra.com/2017/02/automatic-jpa-auditing-persisting-audit-logs-automatically-using-entityListeners.html" target="_blank"> JPA Auditing: Persisting Audit Logs Automatically using EntityListeners</a>, I have discussed how we can use Spring Data JPA automate Auditing and automatically create audit logs or history records and update CreatedBy, CreatedDate, LastModifiedBy, LastModifiedDate properties.<br />
<br />
So in order to save history records for our File entity, we were trying to auto-wire EntityManager inside our FileEntityListener class and we have come to know that we can not do this.<br />
<br />
We can not inject any Spring-managed bean in the EntityListener because EntityListeners are instantiated by JPA before Spring inject anything into it. EntityListeners are not managed Spring so Spring cannot inject any Spring-managed bean e.g. EntityManager in the EntityListeners.<br />
<br />
And this case is not just with EntityListeners, you can not auto wire any Spring-managed bean into another class (i.e. utility classes) which is not managed by Spring.<br />
<br />
Because it is a very common problem and can also arise with other classes so I tried to come out with a common solution which will not just solve this problem but will also help us getting Spring managed beans in other places.<br />
<br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh4rBWtfj9Q_1jyDJqoy7p1-vyPFl-qaWvx1uMiQ_1Czd1GwohIjAPpbcNnFvUS2L6s-0oIdqw-HLFsSmHe8OPvQ6bYNCSjgtNCz0OoYcjwhka2JcvpXmNORk-giEkLPAIHhwNu9k2_VvY/s1600/AutoWiring-Spring-Beans-Into-Classes-Not-Managed-By-Spring-Like-JPA-Entity-Listeners.png" imageanchor="1"><img alt="AutoWiring-Spring-Beans-Into-Classes-Not-Managed-By-Spring-Like-JPA-Entity-Listeners" border="0" height="200" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh4rBWtfj9Q_1jyDJqoy7p1-vyPFl-qaWvx1uMiQ_1Czd1GwohIjAPpbcNnFvUS2L6s-0oIdqw-HLFsSmHe8OPvQ6bYNCSjgtNCz0OoYcjwhka2JcvpXmNORk-giEkLPAIHhwNu9k2_VvY/s640/AutoWiring-Spring-Beans-Into-Classes-Not-Managed-By-Spring-Like-JPA-Entity-Listeners.png" title="AutoWiring-Spring-Beans-Into-Classes-Not-Managed-By-Spring-Like-JPA-Entity-Listeners" width="640" /></a><br />
<br />
So I have created one utility class to fetch any bean according to our requirement.<br />
<br />
<pre><code>@Service
public class BeanUtil implements ApplicationContextAware {
private static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
public static <T> T getBean(Class<T> beanClass) {
return context.getBean(beanClass);
}
}
</code></pre>
<br />
Now to get any a bean in class we will just need call the BeanUtil.getBean(YourClass.class) and pass the class type to it and we will get the bean.<br />
<br />
For Example in our case, we were trying to get the EntityManager bean inside FileEntityListener, we can simply do it by writing BeanUtil.getBean(EntityManager.class).<br />
<br />
<pre><code>public class FileEntityListener {
private void perform(File target, Action action) {
EntityManager entityManager = BeanUtil.getBean(EntityManager.class);
entityManager.persist(new FileHistory(target, action));
}
}
</code></pre>
<br />
You can find complete code on this <a href="https://github.com/njnareshjoshi/articles/tree/master/spring-data-jpa-auditing" target="_blank"> Github Repository</a> and please feel free to provide your valuable feedback.</div>
Naresh Joshihttp://www.blogger.com/profile/01073925481525463593noreply@blogger.com34tag:blogger.com,1999:blog-3832771837877502009.post-56374224564540580072017-02-12T14:57:00.003+05:302020-07-03T00:50:08.347+05:30JPA Auditing: Persisting Audit Logs Automatically using EntityListeners<div dir="ltr" style="text-align: left;" trbidi="on">
In my previous article <a href="https://programmingmitra.com/2017/02/automatic-spring-data-jpa-auditing-saving-CreatedBy-createddate-lastmodifiedby-lastmodifieddate-automatically.html" target="_blank"> Spring Data JPA Auditing: Saving CreatedBy, CreatedDate, LastModifiedBy, LastModifiedDate automatically</a>, I have discussed why Auditing is important for any business application and how we can use Spring Data JPA automate it.<br />
<br />
I have also discussed how Spring Data uses JPA’s <b>EntityListeners</b> and <b>callback methods</b> to automatically update <span style="background-color: #f3f3f3;">CreatedBy</span>, <span style="background-color: #f3f3f3;">CreatedDate</span>, <span style="background-color: white;">LastModifiedBy</span>, <span style="background-color: #f3f3f3;">LastModifiedDate</span> properties.<br />
<br />
Well, here in this article I am going dig a little bit more and discuss how we can use JPA EntityListeners to create audit logs and keep information of every insert, update and delete operation on our data.<br />
<br />
I will take the <span style="background-color: #f3f3f3;">File</span> entity example from the previous article and walk you through the necessary steps and code portions you will need to include in our project to automate the Auditing process.<br />
<br />
We will use Spring Boot, Spring Data JPA (Because it gives us complete JPA functionality plus some nice customization by Spring), MySql to demonstrate this.<br />
<br />
We will need to add below parent and dependencies to our pom file<br />
<br />
<pre><code><parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.1.RELEASE</version>
<relativePath/>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
</code></pre>
<h3 id="implementing-jpa-callback-methods-using-annotations-prepersist-preupdate-preremove">
</h3>
<h3 id="implementing-jpa-callback-methods-using-annotations-prepersist-preupdate-preremove">
</h3>
<h3 id="implementing-jpa-callback-methods-using-annotations-prepersist-preupdate-preremove">
Implementing JPA Callback Methods using annotations @PrePersist, @PreUpdate, @PreRemove</h3>
<br />
JPA provides us the functionality to define callback methods for any entity using annotations <b>@PrePersist</b>, <b>@PreUpdate</b>, <b>@PreRemove</b> and these methods will get invoked before their respective life cycle event.<br />
<br />
Similar to pre-annotations, JPA also provides post annotations like <b>@PostPersist</b>, <b>@PostUpdate</b>, <b>@PostRemove, </b>and<b> @PostLoad</b>. We can use them to define callback methods which will get triggered after the event.<br />
<br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhDTh-4Dmq8NR9o2J2bAiwHNMuilaNYccELNN_UGsfU5nWxtsb22gTIIQKHYrP5BP7utx-c2q4BJBthGQWyxG4mzvXSfRIdrBuVhU2ylGQRXhGR9a8FjR7fWtFKGI9jv5OAwX3Xq3aUECI/s1600/JPA-Automatic-Auditing-Saving-Audit-Logs.png" imageanchor="1"><img alt="JPA-Automatic-Auditing-Saving-Audit-Logs" border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhDTh-4Dmq8NR9o2J2bAiwHNMuilaNYccELNN_UGsfU5nWxtsb22gTIIQKHYrP5BP7utx-c2q4BJBthGQWyxG4mzvXSfRIdrBuVhU2ylGQRXhGR9a8FjR7fWtFKGI9jv5OAwX3Xq3aUECI/s1600/JPA-Automatic-Auditing-Saving-Audit-Logs.png" title="JPA-Automatic-Auditing-Saving-Audit-Logs" /></a><br />
<br />
Name of the annotation can tell you their respective event e.g @PrePersist - Before entity persists and @PostUpdate - After entity gets updated and this is same for other annotations as well.<br />
<h3 id="defining-callback-methods-inside-entity">
</h3>
<h3 id="defining-callback-methods-inside-entity">
Defining callback methods inside entity</h3>
<br />
We can define callback methods inside our entity class but we need to follow some rules like internal callback methods should always return void and take no argument. They can have any name and any access level and can also be static.<br />
<br />
<pre><code>@Entity
public class File {
@PrePersist
public void prePersist() { // Persistence logic }
@PreUpdate
public void preUpdate() { //Updation logic }
@PreRemove
public void preRemove() { //Removal logic }
}
</code></pre>
<h3 id="defining-callback-methods-in-an-external-class-and-use-entitylisteners">
</h3>
<h3 id="defining-callback-methods-in-an-external-class-and-use-entitylisteners">
Defining callback methods in an external class and use @EntityListeners</h3>
<br />
We can also define our callback methods in an external listener class in a manner that they should always return void and accepts target object as the argument. However, they can have any name and any access level and can also be static.<br />
<br />
<pre><code>public class FileEntityListener {
@PrePersist
public void prePersist(File target) { // Persistence logic }
@PreUpdate
public void preUpdate(File target) { //Updation logic }
@PreRemove
public void preRemove(File target) { //Removal logic }
}</code></pre>
<br />
<br />
And we will need to register this <span style="background-color: #f3f3f3;">FileEntityListener</span> class on <span style="background-color: #f3f3f3;">File</span> entity or its superclass by using <b>@EntityListeners</b> annotation<br />
<br />
<pre><code>@Entity
@EntityListeners(FileEntityListener.class)
class File extends Auditable<String> {
@Id
@GeneratedValue
private Integer id;
private String name;
private String content;
// Fields, Getters and Setters
}
</code></pre>
<h3 id="advantages-of-using-entitylisteners">
</h3>
<h3 id="advantages-of-using-entitylisteners">
Advantages of using @EntityListeners</h3>
<div>
<br /></div>
<ul>
<li>First of all, We should not write any kind of business logic in our entity classes and follow Single Responsibility Principle. Every entity class should be <a href="https://programmingmitra.com/2016/05/plain-old-java-object-pojo-explained.html" target="_blank">POJO (Plain Old Java Object)</a>.</li>
<li>We can have only one callback method for a particular event in a single class e.g. only one callback method with @PrePresist is allowed in a class. While we can define more than one listener class in @EntityListeners and every listener class can have a @PrePersist.</li>
</ul>
<br />
For example, I have used @EntityListeners on File and provided FileEntityListener class to it and I have also extended an Auditable class in File class.<br />
<br />
The Auditable class itself have a @EntityListeners on it with AuditingEntityListener class because I am using this class to persist createdBy and other above-mentioned properties, You can check my previous article <a href="https://programmingmitra.com/2017/02/automatic-spring-data-jpa-auditing-saving-CreatedBy-createddate-lastmodifiedby-lastmodifieddate-automatically.html" target="_blank"> Spring Data JPA Auditing: Saving CreatedBy, CreatedDate, LastModifiedBy, LastModifiedDate automatically</a> for more details.<br />
<br />
<pre><code>@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public abstract class Auditable<U> {
@CreatedBy
protected U createdBy;
@CreatedDate
@Temporal(TIMESTAMP)
protected Date createdDate;
@LastModifiedBy
protected U lastModifiedBy;
@LastModifiedDate
@Temporal(TIMESTAMP)
protected Date lastModifiedDate;
// Getters and Setters
}
</code></pre>
<br />
We will also need to provide getters, setters, constructors, toString and equals methods to all the entities. However, you may like to look <a href="https://programmingmitra.com/2017/01/Project-Lombok-The-Boilerplate-Code-Extractor.html" target="_blank"> Project Lombok: The Boilerplate Code Extractor</a> if you want to auto-generate these things.<br />
<br />
Now we are all set and we need to implement our logging strategy, we can store history logs of the <span style="background-color: #f3f3f3;">File</span> in a separate history table <span style="background-color: #f3f3f3;">FileHistory.</span><br />
<br />
<pre><code>@Entity
@EntityListeners(AuditingEntityListener.class)
public class FileHistory {
@Id
@GeneratedValue
private Integer id;
@ManyToOne
@JoinColumn(name = "file_id", foreignKey = @ForeignKey(name = "FK_file_history_file"))
private File file;
private String fileContent;
@CreatedBy
private String modifiedBy;
@CreatedDate
@Temporal(TIMESTAMP)
private Date modifiedDate;
@Enumerated(STRING)
private Action action;
public FileHistory() {
}
public FileHistory(File file, Action action) {
this.file = file;
this.fileContent = file.toString();
this.action = action;
}
// Getters, Setters
}
</code></pre>
<br />
Here Action is an enum<br />
<br />
<pre><code>public enum Action {
INSERTED("INSERTED"),
UPDATED("UPDATED"),
DELETED("DELETED");
private final String name;
private Action(String value) {
this.name = value;
}
public String value() {
return this.name;
}
@Override
public String toString() {
return name;
}
}
</code></pre>
<br />
And we will need to insert an entry in FileHistory for every insert, update, delete operation and we need to write that logic inside our FileEntityListener class. For this purpose, we will need to inject either repository class or EntityManager in FileEntityListener class.<br />
<br />
<h3 style="text-align: left;">
Injecting Spring Managed Beans like EntityManager in EntityListeners</h3>
<br />
But here we have a problem, EntityListeners are instantiated by JPA not Spring, So Spring cannot inject any Spring-managed bean e.g. EntityManager in any EntityListeners.<br />
<br />
So if you try to auto-wire EntityManager inside FileEntityListener class, it will not work<br />
<br />
<pre><code>@Autowired EntityManager entityManager; //Will not work and entityManager will be null always
</code></pre>
<br />
I have also written a separate article on how to <a href="https://programmingmitra.com/2017/03/AutoWiring-Spring-Beans-Into-Classes-Not-Managed-By-Spring-Like-JPA-Entity-Listeners.html" target="_blank">AutoWire Spring Beans Into Classes Not Managed By Spring Like JPA Entity Listeners</a>, you can read it if you want to know more.<br />
<br />
And I am using the same idea here to make it work, we will create a utility class to fetch Spring managed beans for us<br />
<br />
<pre><code>@Service
public class BeanUtil implements ApplicationContextAware {
private static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
public static <T> T getBean(Class<T> beanClass) {
return context.getBean(beanClass);
}
}
</code></pre>
<br />
And now we will write history record creation logic inside FileEntityListener<br />
<br />
<pre><code>public class FileEntityListener {
@PrePersist
public void prePersist(File target) {
perform(target, INSERTED);
}
@PreUpdate
public void preUpdate(File target) {
perform(target, UPDATED);
}
@PreRemove
public void preRemove(File target) {
perform(target, DELETED);
}
@Transactional(MANDATORY)
private void perform(File target, Action action) {
EntityManager entityManager = BeanUtil.getBean(EntityManager.class);
entityManager.persist(new FileHistory(target, action));
}
}
</code></pre>
<br />
And now if we will try to persist or update and file object these auditing properties will automatically get saved.<br />
<br />
You can find complete code on this <a href="https://github.com/njnareshjoshi/articles/tree/master/spring-data-jpa-auditing" target="_blank"> Github Repository</a> and please feel free to provide your valuable feedback.</div>
Naresh Joshihttp://www.blogger.com/profile/01073925481525463593noreply@blogger.com6tag:blogger.com,1999:blog-3832771837877502009.post-82430917628617496272017-02-10T22:21:00.002+05:302020-07-03T00:55:53.301+05:30Spring Data JPA Auditing: Saving CreatedBy, CreatedDate, LastModifiedBy, LastModifiedDate automatically<div dir="ltr" style="text-align: left;" trbidi="on">
In any business application auditing simply means tracking and logging every change we do in the persisted records which simply means tracking every insert, update and delete operation and storing it.<br />
<br />
Auditing helps us in maintaining history records which can later help us in tracking user activities. If implemented properly auditing can also provide us similar functionality like version control systems.<br />
<br />
I have seen projects storing these things manually and doing so become very complex because you will need to write it completely by your own which will definitely require lots of code and lots of code means less maintainability and less focus on writing business logic.<br />
<br />
But why should someone need to go to this path when both JPA and Hibernate provides Automatic Auditing which we can be easily configured in your project.<br />
<br />
And here in this article, I will discuss how we can configure JPA to persist CreatedBy, CreatedDate, LastModifiedBy, LastModifiedDate columns automatically for any entity.<br />
<br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgTGISAfDoL-VSgPymNXWriVAKBWt25TB9BTvbDmSBQn8I7lkMPgsz9Yb6pNkxK9oNtSyWD09uwJQFBOe2dukm4KJVtRu0WZaECATuZcDqZknZ5lFdmdD-u4yCuiK4VXs-4N2k8iZlr5ks/s1600/Spring-Data-JPA-Automatic_Auditing.png" imageanchor="1"><img alt="Spring-Data-JPA-Automatic-Auditing-Saving-CreatedBy-CreatedDate-LastModifiedBy-LastModifiedDate-Automatically" border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgTGISAfDoL-VSgPymNXWriVAKBWt25TB9BTvbDmSBQn8I7lkMPgsz9Yb6pNkxK9oNtSyWD09uwJQFBOe2dukm4KJVtRu0WZaECATuZcDqZknZ5lFdmdD-u4yCuiK4VXs-4N2k8iZlr5ks/s1600/Spring-Data-JPA-Automatic_Auditing.png" title="Spring-Data-JPA-Automatic-Auditing-Saving-CreatedBy-CreatedDate-LastModifiedBy-LastModifiedDate-Automatically" /></a><br />
<br />
<br />
I will walk you through to the necessary steps and code portions you will need to include in your project to automatically update these properties. We will use Spring Boot, Spring Data JPA, MySql to demonstrate this. We will need to add below parent and dependencies to our pom file<br />
<br />
<pre><code><parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.1.RELEASE</version>
<relativePath/>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
</code></pre>
<h3 id="createdby-createddate-lastmodifiedby-and-lastmodifieddate">
</h3>
<h3 id="createdby-createddate-lastmodifiedby-and-lastmodifieddate">
Spring Data Annotations @CreatedBy, @CreatedDate, @LastModifiedBy and @LastModifiedDate</h3>
<br />
Let’s suppose we have a <span style="background-color: #eeeeee;">File</span> entity and a single record in file table stores name and content of the file and we also want to store who created and modified any file at what time. So we can keep track like when the file was created by whom and when it was last modified by whom.<br />
<br />
So we will need to add <span style="background-color: #eeeeee;">name</span>, <span style="background-color: #eeeeee;">content</span>, <span style="background-color: #eeeeee;">createdBy</span>, <span style="background-color: #eeeeee;">createdDate</span>, <span style="background-color: #eeeeee;">lastModifiedBy</span>, <span style="background-color: #eeeeee;">lastModifiedDate</span> properties to our <span style="background-color: #eeeeee;">File</span> entity and to make it more appropriate we can move createdBy, createdDate, lastModifiedBy, lastModifiedDate properties to a base class <span style="background-color: #eeeeee;">Auditable</span> and annotate this base class by <strong> @MappedSuperClass a</strong>nd later we can use the Auditable class in other audited entities.<br />
<br />
<blockquote class="tr_bq">
You will also need to write getters, setters, constructors, toString, equals along with these fields. However, you should take a look at <a href="https://programmingmitra.com/2017/01/Project-Lombok-The-Boilerplate-Code-Extractor.html" target="_blank">Project Lombok: The Boilerplate Code Extractor</a>, if you want to auto-generate these things.</blockquote>
<br />
Both classes will look like<br />
<br />
<pre><code>@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public abstract class Auditable<U> {
@CreatedBy
protected U createdBy;
@CreatedDate
@Temporal(TIMESTAMP)
protected Date creationDate;
@LastModifiedBy
protected U lastModifiedBy;
@LastModifiedDate
@Temporal(TIMESTAMP)
protected Date lastModifiedDate;
// Getters and Setters
}
@Entity
public class File extends Auditable<String> {
@Id
@GeneratedValue
private int id;
private String name;
private String content;
// Getters and Setters
}
</code></pre>
<br />
As you can see above I have used @CreatedBy, @CreatedDate, @LastModifiedBy and @LastModifiedDate annotation on respective fields.<br />
<br />
Spring Data JPA approach abstracts working with JPA callbacks and provides us these fancy annotations to automatically save and update auditing entities.<br />
<br />
<h3 id="use-auditingentitylistener-class-with-entitylisteners">
</h3>
<h3 id="use-auditingentitylistener-class-with-entitylisteners">
Using AuditingEntityListener class with @EntityListeners</h3>
<br />
Spring Data JPA provides a JPA entity listener class <strong> AuditingEntityListener </strong>which contains the callback methods (annotated with <span style="background-color: white;"><b>@PrePersist</b></span> and <span style="background-color: white;"><b>@PreUpdate</b></span> annotation) which will be used to persist and update these properties when we will persist or update our entity.<br />
<br />
JPA provides the <b>@EntityListeners</b> annotation to specify callback listener classes which we use to register our AuditingEntityListener class.<br />
<br />
However, We can also define our own callback listener classes if we want to and specify them using @EntityListeners annotation. In my next article, I will demonstrate how we can use @EntityListeners to store audit logs.<br />
<br />
<h3 style="text-align: left;">
Auditing Author using AuditorAware and Spring Security</h3>
<br />
JPA can analyze createdDate and lastModifiedDate using current system time but what about the createdBy and lastModifiedBy fields, how JPA will recognize what to store in these fields?<br />
<br />
To tell JPA about currently logged in user we will need to provide an implementation of <strong> AuditorAware </strong>and override <span style="background-color: #eeeeee;">getCurrentAuditor()</span> method. And inside <span style="background-color: #eeeeee;">getCurrentAuditor()</span><span style="background-color: white;"> we will need to fetch currently logged in user.</span><br />
<span style="background-color: white;"><br /></span> <span style="background-color: white;">As of now, I have provided a hard-coded user but you are using Spring security then you use it find currently logged in user same as I have mentioned in the comment. </span><br />
<br />
<pre><code>public class AuditorAwareImpl implements AuditorAware<String> {
@Override
public String getCurrentAuditor() {
return "Naresh";
// Can use Spring Security to return currently logged in user
// return ((User) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername()
}
}
</code></pre>
<h3 id="enable-jpa-aditing-by-using-enablejpaauditing">
</h3>
<h3 id="enable-jpa-aditing-by-using-enablejpaauditing">
Enable JPA Auditing by using @EnableJpaAuditing</h3>
<br />
We will need to create a bean of type AuditorAware and will also need to enable JPA auditing by specifying <strong> @EnableJpaAuditing </strong> on one of our configuration class. @EnableJpaAuditing accepts one argument <span style="background-color: #eeeeee;">auditorAwareRef</span> where we need to pass the name of the AuditorAware bean.<br />
<br />
<pre><code>@Configuration
@EnableJpaAuditing(auditorAwareRef = "auditorAware")
public class JpaConfig {
@Bean
public AuditorAware<String> auditorAware() {
return new AuditorAwareImpl();
}
}
</code></pre>
<br />
And now if we will try to persist or update and file object CreatedBy, CreatedDate, LastModifiedBy, LastModifiedDate properties will automatically get saved.<br />
<br />
In the next article <a href="https://programmingmitra.com/2017/02/automatic-jpa-auditing-persisting-audit-logs-automatically-using-entityListeners.html" target="_blank">JPA Auditing: Persisting Audit Logs Automatically using EntityListeners</a>, I have discussed how we can use JPA EntityListeners to create audit logs and generate history records for every insert, update and delete operation.<br />
<br />
You can find complete code on this <a href="https://github.com/njnareshjoshi/articles/tree/master/spring-data-jpa-auditing" target="_blank"> Github Repository</a> and please feel free to give your valuable feedback.</div>
Naresh Joshihttp://www.blogger.com/profile/01073925481525463593noreply@blogger.com48tag:blogger.com,1999:blog-3832771837877502009.post-78640474153204410542017-01-28T15:51:00.001+05:302020-07-03T00:57:16.202+05:30Project Lombok : The Boilerplate Code Extractor<div dir="ltr" style="text-align: left;" trbidi="on">
Lombok is a tool that generates code like getters, setters, constructors, equals, hashCode, toString for us in the same way that our IDE does. While IDE generates all these things in our source code file, Lombok generates them directly in the class file.<br />
<br />
So Lombok basically takes out all these things from your source code to bytecode so we don't need to write them in our source code which means less code in our source code file. And in this article, I am going to explain how Lombok can help us in removing this kind of boilerplate code.<br />
<br />
To understand it let's suppose we have an entity class <span style="background-color: #cccccc;">Employee</span> and we want to use it to hold a single employee record. We can use it as a DTO or persistent entity or anything else we want but idea is that we want to use it to store <span style="background-color: #cccccc;">id</span>, <span style="background-color: #cccccc;">firstName</span>, <span style="background-color: #cccccc;">lastName</span> and <span style="background-color: #cccccc;">salary</span> fields.<br />
<br />
For this requirement, we will need a simple <span style="background-color: #cccccc;">Employee</span> POJO and according to <a href="https://programmingmitra.com/2016/05/plain-old-java-object-pojo-explained.html"> General directions for creating Plain Old Java Object</a>,<br />
<ul>
<li>Each variable in a POJO should be declared as private.</li>
<li>Default constructor should be overridden with public accessibility.</li>
<li>Each variable should have its Setter-Getter method with public accessibility.</li>
<li>POJO should override <span style="background-color: #cccccc;">equals()</span>, <span style="background-color: #cccccc;">hashCode()</span> and <span style="background-color: #cccccc;">toString()</span> methods of Object.</li>
</ul>
And generally our <span style="background-color: #cccccc;">Employee</span> class will look like<br />
<br />
<pre><code>public class Employee {
private long id;
private int salary;
private String firstName;
private String lastName;
public Employee() {
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Employee employee = (Employee) o;
if (id != employee.id) return false;
if (salary != employee.salary) return false;
if (!firstName.equals(employee.firstName)) return false;
if (!lastName.equals(employee.lastName)) return false;
return true;
}
@Override
public int hashCode() {
int result = (int) (id ^ (id >>> 32));
result = 31 * result + firstName.hashCode();
result = 31 * result + lastName.hashCode();
result = 31 * result + salary;
return result;
}
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", salary=" + salary +
'}';
}
}
</code></pre>
<br />
But generally, we always use auto-generation strategies of our IDE to generate getters, setters, default constructor, <span style="background-color: #cccccc;">hashCode</span>, <span style="background-color: #cccccc;">equals</span> and <span style="background-color: #cccccc;">toString</span> e.g. <span style="background-color: #cccccc;">alt+insert</span> in IntelliJ.<br />
<br />
As you can see the size of <span style="background-color: #cccccc;">Employee</span> class is more than 50 lines where field declaration is contributing only 4 lines. And these things are not directly contributing anything to our business logic but just increasing the size of our code.<br />
<br />
Project Lombok provides a way to remove above boilerplate code and simplify development process while still providing these functionalities at the bytecode level. With project Lombok, we can combine all these things within 10 lines<br />
<br />
<pre><code>@Data
public class Employee {
private long id;
private int salary;
private String firstName;
private String lastName;
}
</code></pre>
<br />
With <b>@Data</b> annotation on top of our class Lombok will process our Java source code and produce a class file which will have getters, setters, default arg constructor, hasCode, equals and toString methods in it. So basically Lombok is doing the trick and instead of us adding all those things in our source code and then compiling it a class file Lombok is automatically adding all these things directly to our class files.<br />
<br />
But if we need to write some business code in our getters or setters or in any of above method or we want trick these methods to function a little bit differently, we can still write that method in our class and Lombok will not override it while producing all these stuff in bytecode.<br />
<br />
In order to make it works, we need to<br />
<ol>
<li>Install Lombok plugin in our IDE e.g. In IntelliJ we can install it from Settings -> Plugins -> Browse Repositories window.<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgNVz-NbkR0HcQ2xKcdh5ReRYFtVDIzvpZIdN-vxE6PE7pxBH33ygnjnJ-hN3nR8AwTnTva15YgC3AYnJ5b9JDfQUdMLjAA0m0UJ9LKd7LUp4Tnm7NVQ4Avgq_4Sm-xgcJuwh-CV-bSzY4/s1600/lombok+2.png"><img alt="installing-lombok-plugin-in-intellij-idea" border="0" height="374" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgNVz-NbkR0HcQ2xKcdh5ReRYFtVDIzvpZIdN-vxE6PE7pxBH33ygnjnJ-hN3nR8AwTnTva15YgC3AYnJ5b9JDfQUdMLjAA0m0UJ9LKd7LUp4Tnm7NVQ4Avgq_4Sm-xgcJuwh-CV-bSzY4/s640/lombok+2.png" title="installing-lombok-plugin-in-intellij-idea" width="640" /></a></li>
<li>Enable annotation processing e.g. In IntelliJ we need to check “Enable annotation processing” option on Settings -> Compiler -> Annotation Processors window.<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhtotrUMEsG4iw4DzxScJ6pwCbM8pvsRn2EikC0RY8eQbSj32YkXnt4xYb8A5B0cSM6buMgJchq0CXzUefviZ1sMX03rIjMKNSr8P5kzroxYpTFiG1g9dfCQTRo1Qt4Bg3OE26gYFaMHPk/s1600/lombok+3.png"><img alt="enabling-annotation-in-intellij-idea" border="0" height="372" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhtotrUMEsG4iw4DzxScJ6pwCbM8pvsRn2EikC0RY8eQbSj32YkXnt4xYb8A5B0cSM6buMgJchq0CXzUefviZ1sMX03rIjMKNSr8P5kzroxYpTFiG1g9dfCQTRo1Qt4Bg3OE26gYFaMHPk/s640/lombok+3.png" title="enabling-annotation-in-intellij-idea" width="640" /></a>
</li>
<li>Include Lombok jar in our build path, we can do it by adding the Lombok dependency in pom.xml file if we are using maven or we will need to download the Lombok jar manually and add it to our classpath. <pre><code><dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.12</version>
<optional>true</optional>
<dependency>
</code></pre>
</li>
</ol>
Lombok provides a variety of annotations which we can use and manipulate according to our need. Some of these annotations are<br />
<ul>
<li>
<strong> @NonNull </strong> Can be used with fields, methods, parameters, and local variables to check for NullPointerException.</li>
<li>
<strong> @Cleanup </strong> Provides automatic resource management and ensures the variable declaration that you annotate will be cleaned up by calling its close method. Seems similar to Java’s try-with-resource. <br />
<pre><code>@Cleanup InputStream in = new FileInputStream("filename");
</code></pre>
</li>
<li>
<strong> @Getter/@Setter </strong> Can be used on class or field to generate getters and setters automatically for every field inside the class or for a particular field respectively. <br />
<pre><code>@Getter @Setter private long id;
</code></pre>
</li>
<li>
<strong> @ToString </strong> Generates a default toString method <br />
</li>
<li>
<strong> @EqualsAndHashCode </strong> Generates hashCode and equals implementations from the fields of your object. <br />
<pre><code>@ToString(exclude = "salary")
@EqualsAndHashCode(exclude = "salary")
</code></pre>
</li>
<li>
<strong> @NoArgsConstructor </strong> , <strong> @RequiredArgsConstructor </strong> and <strong> @AllArgsConstructor </strong> Generates constructors that take no arguments, one argument per final / non-null field, or one argument for every field. <br />
</li>
<li>
<strong> @Data </strong> A shortcut for <strong> @ToString </strong> , <strong> @EqualsAndHashCode </strong> , <strong> @Getter </strong> on all fields, and <strong> @Setter </strong> on all non-final fields, and <strong> @RequiredArgsConstructor </strong> . <br />
</li>
<li>
<strong> @Value </strong> is the immutable variant of <strong> @Data</strong>, Helps in making our class Immutable. <br />
</li>
<li>
<strong> @Builder </strong> annotation will generate nice static factory methods in our class which we can use to create objects of our class in more oriented manner e.g. if we will add “@Builder” annotation to our Employee class then we can create object of Employee in the following manner <br />
<pre><code>Employee emp = Employee.builder()
.firstName("Naresh")
.lastName("Joshi")
.build();
</code></pre>
</li>
<li>
<strong> @SneakyThrows </strong> Allows us to throw checked exceptions without actually declaring this in our method’s throws clause, e.g. <br />
<pre><code>@SneakyThrows(Exception.class)
public void doSomeThing() {
// According to some business condition throw some business exception
throw new Exception();
}
</code></pre>
</li>
<li>
<strong> @Synchronized </strong> A safer variant of the synchronized method modifier. <br />
</li>
<li><strong>@CommonsLog, @JBossLog, @Log, @Log4j, @Log4j2, @Slf4j </strong> and <strong> @XSlf4j </strong> which produces log fields in our class and let us use that field for logging. e.g. If we will mark a class with <span style="background-color: #cccccc;">@CommonsLog</span> Lombok will attach below field to our class. <br />
<pre><code>private static final org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog(YourClass.class);
</code></pre>
</li>
</ul>
You can also go to the official website of project <a href="https://projectlombok.org/features/index.html">Lombok</a> for the complete feature list and examples.<br />
<h3 id="advantages-of-lombok">
Advantages of Lombok</h3>
<ul>
<li>Lombok helps us remove boilerplate code and decrease line of unnecessary code</li>
<li>It makes our code highly maintainable, we don’t need to worry about regenerating hashCode, equals, toString, getters, and setters whenever we change our properties.</li>
<li>Lombok provides an efficient builder API to build our object by using <span style="background-color: #cccccc;">@Builder</span></li>
<li>Lombok provides efficient way to make our class Immutable by using @Value</li>
<li>Provides other annotations like <span style="background-color: #cccccc;">@Log</span> - for logging, <span style="background-color: #cccccc;">@Cleanup</span> - for cleaning resources automatically, <span style="background-color: #cccccc;">@SneakyThrows </span> - for throwing checked exception without adding try-catch or throws statement and <span style="background-color: #cccccc;">@Synchronized</span> to make our methods synchronized.</li>
</ul>
<h3 id="disadvantages-of-lombok">
Disadvantages of Lombok</h3>
The only disadvantage Lombok comes with is its dependency, If you are using it then everyone in your project must use it and configure it (install the plugin and enable annotation processing) to successfully compile the project. And all your project mates need to be aware of it otherwise, they will not be able to build the project and receive lots of compilation errors. However, this is only an initial step and will not take more than a couple of minutes.</div>
Naresh Joshihttp://www.blogger.com/profile/01073925481525463593noreply@blogger.com6tag:blogger.com,1999:blog-3832771837877502009.post-50403696321518108582017-01-14T12:30:00.004+05:302020-07-03T00:58:44.894+05:30Java Cloning - Why Even Copy Constructors Are Not Sufficient<div dir="ltr" style="text-align: left;" trbidi="on">
This is my third article on <a href="https://programmingmitra.com/search/label/Java%20Cloning?max-results=6"> Java Cloning</a> series, In previous articles <a href="https://programmingmitra.com/2016/11/Java-Cloning-Types-of-Cloning-Shallow-Deep-in-Details-with-Example.html"> Java Cloning and Types of Cloning (Shallow and Deep) in Details with Example</a> and <a href="https://programmingmitra.com/2017/01/Java-cloning-copy-constructor-versus-Object-clone-or-cloning.html"> Java Cloning - Copy Constructor versus Cloning</a> I had discussed Java cloning in detail and explained every concept like what is cloning, how does it work, what are the necessary steps we need to follow to implement cloning, how to use Object.clone(), what is Shallow and Deep cloning, <a href="https://www.programmingmitra.com/2019/08/how-to-deep-clone-an-object-using-java-in-memory-serialization.html" target="_blank">how to achieve cloning using serialization</a> and Copy constructors and advantages copy of copy constructors over Java cloning.<br />
<br />
If you have read those articles you can easily understand why it is good to use Copy constructors over cloning or Object.clone(). In this article, I am going to discuss why copy constructors are not sufficient?<br />
<br />
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiv4WWogReXV277-SoJpnanLPZQlzeTRfAhQY7xGddMI0berq8K1qrj9oRwnJfG4SdLx_c9LDn7TSYAmCtYZd4mj_IS6-0VXnyUnyco1XgRas_8HBjReDw86xVs7UZ0MH4RySXfr44ye60/s1600/Why-Copy-Constructors-Are-Not-Sufficient.png" imageanchor="1"><img alt="Why-Copy-Constructors-Are-Not-Sufficient" border="0" height="330" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiv4WWogReXV277-SoJpnanLPZQlzeTRfAhQY7xGddMI0berq8K1qrj9oRwnJfG4SdLx_c9LDn7TSYAmCtYZd4mj_IS6-0VXnyUnyco1XgRas_8HBjReDw86xVs7UZ0MH4RySXfr44ye60/s640/Why-Copy-Constructors-Are-Not-Sufficient.png" title="Why-Copy-Constructors-Are-Not-Sufficient" width="640" /></a><br />
<br />
Yes, you are reading it right copy constructors are not sufficient by themselves, copy constructors are not polymorphic because constructors do not get inherited to the child class from the parent class. If we try to refer a child object from parent class reference, we will face problems in cloning it using the copy constructor. To understand it let’s take examples of two classes <span style="background-color: #cccccc;">Mammal</span> and <span style="background-color: #cccccc;">Human</span> where <span style="background-color: #cccccc;">Human</span> extends <span style="background-color: #cccccc;">Mammal</span>, <span style="background-color: #cccccc;">Mammal</span> class have one field <span style="background-color: #cccccc;">type</span> and two constructors, one to create the object and one copy constructor to create a copy of an object<br />
<br />
<pre><code>class Mammal {
protected String type;
public Mammal(String type) {
this.type = type;
}
public Mammal(Mammal original) {
this.type = original.type;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Mammal mammal = (Mammal) o;
if (!type.equals(mammal.type)) return false;
return true;
}
@Override
public int hashCode() {
return type.hashCode();
}
@Override
public String toString() {
return "Mammal{" + "type='" + type + "'}";
}
}
</code></pre>
<br />
And <span style="background-color: #cccccc;">Human</span> class which extends <span style="background-color: #cccccc;">Mammal</span> class, have one <span style="background-color: #cccccc;">name</span> field, one normal constructor and one copy constructor to create a copy<br />
<br />
<pre><code>class Human extends Mammal {
protected String name;
public Human(String type, String name) {
super(type);
this.name = name;
}
public Human(Human original) {
super(original.type);
this.name = original.name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
Human human = (Human) o;
if (!type.equals(human.type)) return false;
if (!name.equals(human.name)) return false;
return true;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + name.hashCode();
return result;
}
@Override
public String toString() {
return "Human{" + "type='" + type + "', name='" + name + "'}";
}
}
</code></pre>
<br />
<blockquote>
Here in both copy constructors we are doing deep cloning.
</blockquote>
<br />
Now let’s create objects for both classes<br />
<br />
<pre><code>Mammal mammal = new Mammal("Human");
Human human = new Human("Human", "Naresh");
</code></pre>
<br />
Now if we want to create a clone for <span style="background-color: #cccccc;">mammal</span> or <span style="background-color: #cccccc;">human</span>, we can simply do it by calling their respective copy constructor<br />
<br />
<pre><code>Mammal clonedMammal = new Mammal(mammal);
Human clonedHuman = new Human(human);
</code></pre>
<br />
We will get no error in doing this and both objects will be cloned successfully, as we can see below tests<br />
<br />
<pre><code>System.out.println(mammal == clonedMammal); // false
System.out.println(mammal.equals(clonedMammal)); // true
System.out.println(human == clonedHuman); // false
System.out.println(human.equals(clonedHuman)); // true
</code></pre>
<br />
But what if we try to refer object of <span style="background-color: #cccccc;">Human</span> from the reference of <span style="background-color: #cccccc;">Mammal</span><br />
<br />
<pre><code>Mammal mammalHuman = new Human("Human", "Mahesh");
</code></pre>
<br />
In order to clone <span style="background-color: #cccccc;">mammalHuman</span>, we can not use constructor <span style="background-color: #cccccc;">Human</span>, It will give us compilation error because type <span style="background-color: #cccccc;">mammalHuman</span> is <span style="background-color: #cccccc;">Mammal</span> and constructor of <span style="background-color: #cccccc;">Human</span> class accept <span style="background-color: #cccccc;">Human</span>.<br />
<br />
<pre><code>Mammal clonedMammalHuman = new Human(mammalHuman); // compilation error
</code></pre>
<br />
And if we try clone <span style="background-color: #cccccc;">mammalHuman</span> using copy constructor of <span style="background-color: #cccccc;">Mammal</span>, we will get the object of <span style="background-color: #cccccc;">Mammal</span> instead of <span style="background-color: #cccccc;">Human</span> but <span style="background-color: #cccccc;">mammalHuman</span> holds the object of <span style="background-color: #cccccc;">Human</span><br />
<br />
<pre><code>Mammal clonedMammalHuman = new Mammal(mammalHuman);
</code></pre>
<br />
So both <span style="background-color: #cccccc;">mammalHuman</span> and <span style="background-color: #cccccc;">clonedMammalHuman</span> are not the same objects as you see in the output below code<br />
<br />
<pre><code>System.out.println("Object " + mammalHuman + " and copied object " + clonedMammalHuman + " are == : " + (mammalHuman == clonedMammalHuman));
System.out.println("Object " + mammalHuman + " and copied object " + clonedMammalHuman + " are equal : " + (mammalHuman.equals(clonedMammalHuman)) + "\n");
</code></pre>
<br />
Output:<br />
<br />
<pre><code>Object Human{type='Human', name='Mahesh'} and copied object Mammal{type='Human'} are == : false
Object Human{type='Human', name='Mahesh'} and copied object Mammal{type='Human'} are equal : false
</code></pre>
<br />
As we can see copy constructors suffer from inheritance problems and they are not polymorphic as well. So how can we solve this problem, Well there various solutions like creating static Factory methods or creating some generic class which will do this for us and the list will go on?<br />
<br />
But there is a very easy solution which will require copy constructors and will be polymorphic as well. We can solve this problem using defensive copy methods, a method which we are going to include in our classes and call copy constructor from it and again override it the child class and call its copy constructor from it.<br />
<br />
Defensive copy methods will also give us the advantage of dependency injection, we can inject dependency instead of making our code tightly coupled we can make it loosely coupled, we can even create an interface which will define our defensive copy method and then implement it in our class and override that method.<br />
<br />
So in <span style="background-color: #cccccc;">Mammal</span> class, we will create a no-argument method <span style="background-color: #cccccc;">cloneObject</span> however, we are free to name this method anything like <span style="background-color: #cccccc;">clone </span>or <span style="background-color: #cccccc;">copy</span> or <span style="background-color: #cccccc;">copyInstance</span><br />
<br />
<pre><code>public Mammal cloneObject() {
return new Mammal(this);
}
</code></pre>
<br />
And we can override same in “Human” class<br />
<br />
<pre><code>@Override
public Human cloneObject() {
return new Human(this);
}
</code></pre>
<br />
Now to clone <span style="background-color: #cccccc;">mammalHuman</span> we can simply say<br />
<br />
<pre><code>Mammal clonedMammalHuman = mammalHuman.clone();
</code></pre>
<br />
And for the last two sys out we will get below output which is our expected behaviour.<br />
<br />
<pre><code>Object Human{type='Human', name='Mahesh'} and copied object Human{type='Human', name='Mahesh'} are == : false
Object Human{type='Human', name='Mahesh'} and copied object Human{type='Human', name='Mahesh'} are equal : true
</code></pre>
<br />
As we can see apart from getting the advantage of polymorphism this option also gives us freedom from passing any argument.<br />
<br />
You can found complete code in <a href="https://github.com/njnareshjoshi/exercises/blob/master/src/org/programming/mitra/exercises/CopyConstructorExample.java">CopyConstructorExample Java file on Github</a> and please feel free to give your valuable feedback.</div>
Naresh Joshihttp://www.blogger.com/profile/01073925481525463593noreply@blogger.com4tag:blogger.com,1999:blog-3832771837877502009.post-44537656172218326262017-01-10T21:39:00.002+05:302020-07-03T01:01:04.539+05:30Java Cloning - How Copy Constructors are Better Than Cloning<div dir="ltr" style="text-align: left;" trbidi="on">
In my previous article <a href="https://programmingmitra.com/2016/11/Java-Cloning-Types-of-Cloning-Shallow-Deep-in-Details-with-Example.html" target="_blank"> Java Cloning and Types of Cloning (Shallow and Deep) in Details with Example</a>, I have discussed Java Cloning in details and answered questions about how we can use cloning to copy objects in Java, what are two different types of cloning (Shallow & Deep) and how we can implement both of them, if you haven’t read it please go ahead.<br />
<br />
In order to implement cloning, we need to configure our classes to follow the below steps<br />
<ul>
<li>Implement Cloneable interface in our class or its superclass or interface,</li>
<li>Define clone() method which should handle CloneNotSupportedException (either throw or log),</li>
<li>And in most cases from our clone() method we call the clone() method of the superclass.</li>
</ul>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjbxONpG9dx0dVsPYxTmZNJlOwDF6T8Dhk5ow-icvxzlaryUUF0vSPZxyks7Zn_rH7uM8cvBZn1dQeHzFQSocjTkcIL7OU5cGOvE7s6pNEVLSGH0SeGNRpStySZ75DYqW9gwnt_MJz5cjE/s1600/Java+Cloning.png"><img alt="Java Cloning versus Copy Constructor" border="0" height="232" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjbxONpG9dx0dVsPYxTmZNJlOwDF6T8Dhk5ow-icvxzlaryUUF0vSPZxyks7Zn_rH7uM8cvBZn1dQeHzFQSocjTkcIL7OU5cGOvE7s6pNEVLSGH0SeGNRpStySZ75DYqW9gwnt_MJz5cjE/s640/Java+Cloning.png" title="Java Cloning versus Copy Constructor" width="640" /></a></div>
<br />
And super.clone() will call its super.clone() and the chain will continue until call will reach to clone() method of the Object class which will create a field by field mem copy of our object and return it back.<br />
<br />
Like everything Cloning also comes with its advantages and disadvantages. However, Java cloning is more famous its design issues but still, it is the most common and popular cloning strategy present today.<br />
<h3 id="advantages-of-objectclone">
Advantages of Object.clone()</h3>
<div>
Object.clone() have many design issues but it is still the popular and easiest way of copying objects, Some advantages of using clone() are</div>
<ul>
<li>Cloning requires very less line of code, just an abstract class with 4 or 5 line long clone() method but we will need to override it if we need deep cloning.</li>
<li>It is the easiest way of copying object especially if we are applying it to an already developed or an old project. We just need to define a parent class, implement Cloneable in it, provide the definition of clone() method and we are ready every child of our parent will get the cloning feature. </li>
<li>We should use clone to copy arrays because that’s generally the fastest way to do it.</li>
<li>As of release 1.5, calling clone on an array returns an array whose compile-time <br />type is the same as that of the array being cloned which clearly means calling clone on arrays do not require typecasting.</li>
</ul>
<h3 id="disadvantages-of-objectclone">
Disadvantages of Object.clone()</h3>
Below are some cons due to which many developers don't use Object.clone()<br />
<ul>
<li>Using Object.clone() method requires us to add lots of syntax to our code like implement Cloneable interface, define clone() method and handle CloneNotSupportedException and finally call to Object.clone() and cast it our object.</li>
<li>The Cloneable interface lacks clone() method, actually, Cloneable is a marker interface and doesn’t have any method in it and still, we need to implement it just to tell JVM that we can perform clone() on our object.</li>
<li>Object.clone() is protected so we have to provide our own clone() and indirectly call Object.clone() from it.</li>
<li>We don’t have any control over object construction because Object.clone() doesn’t invoke any constructor.</li>
<li>If we are writing the clone method in a child class e.g. Person then all of its superclasses should define clone() method in them or inherit it from another parent class otherwise super.clone() chain will fail.</li>
<li>Object.clone() support only shallow copy so reference fields of our newly cloned object will still hold objects which fields of our original object were holding. In order to overcome this, we need to implement clone() in every class whose reference our class is holding and then call their clone them separately in our clone() method like in below example.</li>
<li>We can not manipulate final fields in Object.clone() because final fields can only be changed through constructors. In our case, if we want every Person objects to be unique by id we will get the duplicate object if we use Object.clone() because Object.clone() will not call the constructor and final final id field can’t be modified from Person.clone().</li>
</ul>
<pre><code>class City implements Cloneable {
private final int id;
private String name;
public City clone() throws CloneNotSupportedException {
return (City) super.clone();
}
}
class Person implements Cloneable {
public Person clone() throws CloneNotSupportedException {
Person clonedObj = (Person) super.clone();
clonedObj.name = new String(this.name);
clonedObj.city = this.city.clone();
return clonedObj;
}
}
</code></pre>
<br />
Because of the above design issues with Object.clone() developers always prefer other ways to copy objects like using<br />
<ul>
<li>
BeanUtils.cloneBean(object) creates a shallow clone similar to Object.clone().</li>
<li>
SerializationUtils.clone(object) creates a deep clone. (i.e. the whole properties graph is cloned, not only the first level), but all classes must implement Serializable.</li>
<li>
<a href="https://code.google.com/p/cloning/" target="_blank"> Java Deep Cloning Library</a> offers deep cloning without the need to implement Serializable.</li>
</ul>
All these options require the use of some external library plus these libraries will also be using Serialization or Copy Constructors or Reflection internally to copy our object. So if you don’t want to go with the above options or want to write our own code to copy the object then you can use<br />
<ol>
<li>
<strong> Serialization </strong>
</li>
<li>
<strong> Copy Constructors </strong>
</li>
</ol>
<h3 id="serialisation">
Serialization</h3>
As discussed in <a href="https://programmingmitra.com/2016/05/different-ways-to-create-objects-in-java-with-example.html" target="_blank">5 different ways to create objects in Java</a>, deserialising a serialised object creates a new object with the same state as in the serialized object. So similar to above cloning approaches we can achieve deep cloning functionality using object <a href="https://www.programmingmitra.com/2019/08/what-is-serialization-everything-about-java-serialization-explained-with-example.html" target="_blank">serialization and deserialization</a> as well and with this approach we do not have worry about or write code for deep cloning, we get it by default.<br />
<br />
We can do it like it is done below or we can also use other APIs like JAXB which supports serialization.<br />
<br />
<pre><code>// Method to deep clone an object using in memory serialization.
public Employee copy(Person original) throws IOException, ClassNotFoundException {
// First serializing the object and its state to memory using ByteArrayOutputStream instead of FileOutputStream.
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos);
out.writeObject(original);
// And then deserializing it from memory using ByteArrayOutputStream instead of FileInputStream,
// Deserialization process will create a new object with the same state as in the serialized object.
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream in = new ObjectInputStream(bis);
return (Person) in.readObject();
}</code></pre>
<br />
However, cloning an object using serialization comes with some performance overhead and we can improve on it by using in-memory serialization if we just need to clone the object and don’t need to persist it in a file for future use, you can read more on <a href="https://www.programmingmitra.com/2019/08/how-to-deep-clone-an-object-using-java-in-memory-serialization.html" target="_blank">How To Deep Clone An Object Using Java In Memory Serialization</a>.<br />
<h3 id="copy-constructors">
Copy Constructors</h3>
This method copying object is most popular between developer community it overcomes every design issue of Object.clone() and provides better control over object construction<br />
<br />
<pre><code>public Person(Person original) {
this.id = original.id + 1;
this.name = new String(original.name);
this.city = new City(original.city);
}
</code></pre>
<h3 id="advantages-of-copy-constructors-over-objectclone">
Advantages of copy constructors over Object.clone()</h3>
Copy constructors are better than Object.clone() because they<br />
<ul>
<li>Don’t force us to implement any interface or throw any exception but we can surely do it if it is required.</li>
<li>Don’t require any type of cast.</li>
<li>Don’t require us to depend on an unknown object creation mechanism.</li>
<li>Don’t require parent class to follow any contract or implement anything.</li>
<li>Allow us to modify final fields.</li>
<li>Allow us to have complete control over object creation, we can write our initialization logic in it.</li>
</ul>
By using Copy constructors strategy, we can also create conversion constructors which can allow us to convert one object to another object e.g. ArrayList(Collection<? extends E> c) constructor generates an ArrayList from any Collection object and copy all items from Collection object to newly created ArrayList object.<br />
<br />
<br /></div>
Naresh Joshihttp://www.blogger.com/profile/01073925481525463593noreply@blogger.com0tag:blogger.com,1999:blog-3832771837877502009.post-49531699179539604282016-11-20T12:46:00.001+05:302020-07-03T01:03:12.587+05:30Java Cloning and Types of Cloning (Shallow and Deep) in Details with Example<div dir="ltr" style="text-align: left;" trbidi="on">
In my previous article <a href="https://programmingmitra.com/2016/05/different-ways-to-create-objects-in-java-with-example.html"> 5 Different ways to create objects in Java with Example</a>, I have discussed 5 different ways (new keyword, Class.newInstance() method, Constructor.newInstance() method, <a href="https://www.programmingmitra.com/search/label/Java%20Cloning" target="_blank">cloning</a> and <a href="https://www.programmingmitra.com/search/label/Serialization" target="_blank">serialization-deserialization</a>) a developer can use to create objects, if you haven't read it please go ahead.<br />
<br />
Cloning is also a way of creating an object but in general, cloning is not just about creating a new object. Cloning means creating a new object from an already present object and copying all data of a given object to that new object.<br />
<br />
In order to create a clone of an object we generally design our class in such a way that<br />
<ol>
<li>Our class should implement Cloneable interface otherwise, JVM will throw CloneNotSupportedException if we will call clone() on our object.<br />
<blockquote>
Cloneable interface is a marker interface which JVM uses to analyse whether this object is allowed for cloning or not. According to JVM if yourObject instanceof Cloneable then create a copy of the object otherwise throw CloneNotSupportedException.
</blockquote>
</li>
<li>Our class should have a clone method which should handle CloneNotSupportedException. <br />
<blockquote>
It is not necessary to define our method by the name of clone, we can give it any name we want e.g. <span style="background-color: #f3f3f3;">createCopy()</span>. <span style="background-color: #f3f3f3;">Object.clone()</span> method is protected by its definition so practically child classes of Object outside the package of <span style="background-color: #f3f3f3;">Object</span> class (<span style="background-color: #f3f3f3;">java.lang</span>) can only access it through inheritance and within itself. So in order to access clone method on objects of our class we will need to define a <span style="background-color: #f3f3f3;">clone</span> method inside our class and then class <span style="background-color: #f3f3f3;">Object.clone()</span> from it. For details on protected access specifier, please read
<a href="https://programmingmitra.com/2016/10/why-a-java-class-can-not-be-private-or-protected.html">
Why an outer Java class can’t be private or protected
</a>
.
</blockquote>
</li>
<li>And finally, we need to call the clone() method of the superclass, which will call it's super’s clone() and this chain will continue until it will reach to clone() method of the Object class. Object.clone() method is the actual worker who creates the clone of your object and another clone() methods just delegates the call to its parent’s clone(). <br />
</li>
</ol>
<blockquote>
All the things also become disadvantage of the cloning strategy to copy the object because all of above steps are necessary to make cloning work. But we can choose to not do all above things follow other strategies e.g. Copy Constructors, To know more read <a href="https://programmingmitra.com/2017/01/Java-cloning-copy-constructor-versus-Object-clone-or-cloning.html">Java Cloning - Copy Constructor versus Cloning</a>.
</blockquote>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg5cCywYImbEUWg-qTS1vp_JV4Vg1QygMSAFJO2MU8yYdTxidNZuMhTlSMAf5xqVx6ACMoe_Bts5P9-d7LRoMDOW2VIbaVMsZNNYnHMFtIbrE6uaIbXAktMEE2gBkRP9qd1LNWJPuS7o_s/s1600/Java+Cloning.png"><img alt="Java Cloning (Shallow Cloning, Deep Cloning)Example" border="0" height="232" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg5cCywYImbEUWg-qTS1vp_JV4Vg1QygMSAFJO2MU8yYdTxidNZuMhTlSMAf5xqVx6ACMoe_Bts5P9-d7LRoMDOW2VIbaVMsZNNYnHMFtIbrE6uaIbXAktMEE2gBkRP9qd1LNWJPuS7o_s/s640/Java+Cloning.png" title="Java Cloning (Shallow Cloning, Deep Cloning)Example" width="640" /></a></div>
<br />
To demonstrate cloning we will create two classes Person and City and override<br />
<ol>
<li>toString() to show the content of the person object,</li>
<li>equals() and hashCode() method to compare the objects,</li>
<li>clone() to clone the object</li>
</ol>
However, we are overriding the <span style="background-color: #f3f3f3;">clone</span> method but it not necessary we can create a clone method by any name but if we are naming it as <span style="background-color: #f3f3f3;">clone</span> then we will need to follow basic rules of method overriding e.g. method should have same name, arguments and return type (after Java 5 you can also use a covariant type as return type). To know more about method overriding read <a href="https://programmingmitra.com/2017/05/everything-about-method-overloading-vs-method-overriding.html">Everything About Method Overloading Vs Method Overriding</a>.<br />
<br />
<pre><code>class Person implements Cloneable {
private String name; // Will holds address of the String object, instead of object itself
private int income; // Will hold bit representation of int, which is assigned to it
private City city; // Will holds address of the City object, instead of City object
public String getName() {
return name;
}
public void setName(String firstName) {
this.name = firstName;
}
public int getIncome() {
return income;
}
public void setIncome(int income) {
this.income = income;
}
public City getCity() {
return city;
}
public void setCity(City city) {
this.city = city;
}
public Person(String firstName, int income, City city) {
super();
this.name = firstName;
this.income = income;
this.city = city;
}
// But we can also create using any other name
@Override
public Person clone() throws CloneNotSupportedException {
return (Person) super.clone();
}
// To print the person object
@Override
public String toString() {
return "Person [name=" + name + ", income=" + income + ", city=" + city + "]";
}
// hasCode(), and equals() to compare person objects
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((city == null) ? 0 : city.hashCode());
result = prime * result + income;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (city == null) {
if (other.city != null)
return false;
} else if (!city.equals(other.city))
return false;
if (income != other.income)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
</code></pre>
<br />
Person class has a reference to City class which looks like below<br />
<br />
<pre><code>class City implements Cloneable {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public City(String name) {
super();
this.name = name;
}
@Override
public City clone() throws CloneNotSupportedException {
return (City) super.clone();
}
@Override
public String toString() {
return "City [name=" + name + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
City other = (City) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
</code></pre>
<br />
And let's test it<br />
<br />
<pre><code>public class CloningExample {
public static void main(String[] args) throws CloneNotSupportedException {
City city = new City("Dehradun");
Person person1 = new Person("Naresh", 10000, city);
System.out.println(person1);
Person person2 = person1.clone();
System.out.println(person2);
if (person1 == person2) { // Evaluate false, because person1 and person2 holds different objects
System.out.println("Both person1 and person2 holds same object");
}
if (person1.equals(person2)) { // Evaluate true, person1 and person2 are equal and have same content
System.out.println("But both person1 and person2 are equal and have same content");
}
if (person1.getCity() == person2.getCity()) {
System.out.println("Both person1 and person2 have same city object");
}
}
}
</code></pre>
<br />
person1.clone() calls super.clone() which means Object.clone() method.<br />
<blockquote>
Object.clone() method copy content of the object to other object bit-by-bit, means the values of all instance variables from one object will get copied to instance variables of other object.</blockquote>
<br />
<br />
So (person1 == person2) will evaluate false because person1 and person2 are the copy of each other but both are different objects and holds different heap memory. While person1.equals(person2) evaluate true because both have the same content.<br />
<br />
<blockquote>
But as we know reference variables holds address of the object instead of object itself, which can also be referred from other reference variables and if we change one other will reflect that change.
</blockquote>
<br />
So while cloning process Object.clone() will copy address which person1.city is holding to person2.city, So now city, person1.city, and person2.city all are holding the same city object. That’s why (person1.getCity() == person2.getCity()) evaluate true. This behaviour of cloning is known as <strong> Shallow Cloning</strong>.<br />
<br />
<h4 style="text-align: left;">
<strong>Types of Cloning</strong></h4>
This behaviour of Object.clone() method classifies cloning into two sections<br />
<h4 style="text-align: left;">
<strong> 1. Shallow Cloning</strong></h4>
<strong></strong>Default cloning strategy provided by Object.clone() which we have seen. The clone() method of object class creates a new instance and copy all fields of the Cloneable object to that new instance (either it is primitive or reference). So in the case of reference types only reference bits get copied to the new instance, therefore, the reference variable of both objects will point to the same object. The example we have seen above is an example of Shallow Cloning.<br />
<h4 style="text-align: left;">
<strong> 2. Deep Cloning</strong></h4>
<strong></strong>As the name suggests deep cloning means cloning everything from one object to another object. To achieve this we will need to trick our clone() method provide our own cloning strategy. We can do it by implementing Cloneable interface and override clone() method in every reference type we have in our object hierarchy and then call super.clone() and these clone() methods in our object’s clone method.<br />
<br />
So we can change the clone method of Person class in below way<br />
<br />
<pre><code>public Person clone() throws CloneNotSupportedException {
Person clonedObj = (Person) super.clone();
clonedObj.city = this.city.clone();
return clonedObj;
}
</code></pre>
<br />
Now (person1.getCity() == person2.getCity()) will evaluate false because in clone() method of Person class we are clonning city object and assigning it to the new clonned person object.<br />
<br />
In below example we have deep copied city object by implementing clone() in City class and calling that clone() method of person class, That's why person1.getCity() == person2.getCity() evaluate false because both are separate objects. But we have not done same with Country class and person1.getCountry() == person2.getCountry() evaluate true.<br />
<br />
<pre><code>public class CloningExample {
public static void main(String[] args) throws CloneNotSupportedException {
City city = new City("Dehradun");
Country country = new Country("India");
Person person1 = new Person("Naresh", 10000, city, country);
System.out.println(person1);
Person person2 = person1.clone();
System.out.println(person2);
// Evaluate false, because person1 and person2 holds different objects
if (person1 == person2) {
System.out.println("Both person1 and person2 holds same object");
}
// Evaluate true, person1 and person2 are equal and have same content
if (person1.equals(person2)) {
System.out.println("But both person1 and person2 are equal and have same content");
}
// Evaluate false
if (person1.getCity() == person2.getCity()) {
System.out.println("Both person1 and person2 have same city object");
}
// Evaluate true, because we have not implemented clone in Country class
if (person1.getCountry() == person2.getCountry()) {
System.out.println("Both person1 and person2 have same country object");
}
// Now lets change city and country object and print person1 and person2
city.setName("Pune");
country.setName("IN");
// person1 will print new Pune city
System.out.println(person1);
// while person2 will still print Dehradun city because person2.city holds a separate city object
System.out.println(person2);
}
}
class Person implements Cloneable {
private String name; // Will holds address of the String object which lives
// in SCP, instead of String object itself
private int income; // Will hold bit representation of int, which is assigned to it
private City city; // Will holds address of the City object which lives in
// heap, instead of City object
private Country country;
public String getName() {
return name;
}
public void setName(String firstName) {
this.name = firstName;
}
public int getIncome() {
return income;
}
public void setIncome(int income) {
this.income = income;
}
public City getCity() {
return city;
}
public void setCity(City city) {
this.city = city;
}
public Country getCountry() {
return country;
}
public void setCountry(Country country) {
this.country = country;
}
public Person(String name, int income, City city, Country country) {
super();
this.name = name;
this.income = income;
this.city = city;
this.country = country;
}
@Override
public Person clone() throws CloneNotSupportedException {
Person clonedObj = (Person) super.clone();
clonedObj.city = this.city.clone();
return clonedObj;
}
@Override
public String toString() {
return "Person [name=" + name + ", income=" + income + ", city=" + city + ", country=" + country + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((city == null) ? 0 : city.hashCode());
result = prime * result + ((country == null) ? 0 : country.hashCode());
result = prime * result + income;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (city == null) {
if (other.city != null)
return false;
} else if (!city.equals(other.city))
return false;
if (country == null) {
if (other.country != null)
return false;
} else if (!country.equals(other.country))
return false;
if (income != other.income)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
class City implements Cloneable {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public City(String name) {
super();
this.name = name;
}
public City clone() throws CloneNotSupportedException {
return (City) super.clone();
}
@Override
public String toString() {
return "City [name=" + name + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
City other = (City) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
class Country {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Country(String name) {
super();
this.name = name;
}
@Override
public String toString() {
return "Country [name=" + name + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Country other = (Country) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
</code></pre>
<br />
Java cloning is not considered a good way to copy an object and lots of other ways are there to do the same. You can read <a href="https://programmingmitra.com/2017/01/Java-cloning-copy-constructor-versus-Object-clone-or-cloning.html">Java Cloning - Copy Constructor versus Cloning</a> to get more knowledge on why Java cloning is not a preferred way of cloning and what are other ways to overcome this.</div>
Naresh Joshihttp://www.blogger.com/profile/01073925481525463593noreply@blogger.com6