Marker interfaces are a design pattern with run-time type checking that allows you to associate an interface and a class. To understand why this might be necessary, consider an example of marking the Serializible class with a marker. Let's assume that we needed to save the state of an object in memory, and then also be able to decrypt what we saved. Then, you say, we can convert our object into a set of bits. Right. We can use a simple way of writing to a file using FileInputStream, but this is only convenient if there are few objects, but what if there are many of them? There is a wonderful serialization tool for this. The main rule when you use it is that the object being serialized must contain all the data and not refer to other objects. Look at your class “Aha, the fields are not referenced and it’s good to put the Serializable marker.” And when you put it, it will mean that the objects that you marked can be written to ObjectOutputStream. The ObjectOutputStream class has a writeObject0() method, and it contains instanceof checks that check whether the object can be written and if the entire series of checks fails, then a NotSerializableException exception is thrown, and if not, everything is neatly written to memory. Let's create a BigObject class, the instances of which we will serialize.
package post1; import java.io.Serializable; public class BigObject implements Serializable { private int id; public void setId(final int id){ this.id = id; } public int getId() { return id; } }
The BigObject class is already marked as Serializable. It has one id field and accompanying get/set methods. package post1; import post1.BigObject; import java.io.*; public class InterfaceMarker { public static void main(String[] args) throws IOException, ClassNotFoundException { int originalId = 12; BigObject objectOriginal = new BigObject(); objectOriginal.setId(originalId); ByteArrayOutputStream writeBuffer = new ByteArrayOutputStream(); ObjectOutputStream outputStream = new ObjectOutputStream(writeBuffer); outputStream.writeObject(objectOriginal); outputStream.close(); byte[] buffer = writeBuffer.toByteArray(); ByteArrayInputStream readBuffer = new ByteArrayInputStream(buffer); ObjectInputStream inputStream = new ObjectInputStream(readBuffer); BigObject objectCopy = (BigObject)inputStream.readObject(); if (objectCopy.getId() == originalId) System.out.println( "originalId equals copiedId"); } }
GO TO FULL VERSION