Serialize interface in java

Interface Serializable

Warning: Deserialization of untrusted data is inherently dangerous and should be avoided. Untrusted data should be carefully validated according to the «Serialization and Deserialization» section of the Secure Coding Guidelines for Java SE. Serialization Filtering describes best practices for defensive use of serial filters.

Classes that do not implement this interface will not have any of their state serialized or deserialized. All subtypes of a serializable class are themselves serializable. The serialization interface has no methods or fields and serves only to identify the semantics of being serializable.

It is possible for subtypes of non-serializable classes to be serialized and deserialized. During serialization, no data will be written for the fields of non-serializable superclasses. During deserialization, the fields of non-serializable superclasses will be initialized using the no-arg constructor of the first (bottommost) non-serializable superclass. This constructor must be accessible to the subclass that is being deserialized. It is an error to declare a class Serializable if this is not the case; the error will be detected at runtime. A serializable subtype may assume responsibility for saving and restoring the state of a non-serializable supertype’s public, protected, and (if accessible) package-access fields. See the Java Object Serialization Specification, section 3.1, for a detailed specification of the deserialization process, including handling of serializable and non-serializable classes.

When traversing a graph, an object may be encountered that does not support the Serializable interface. In this case the NotSerializableException will be thrown and will identify the class of the non-serializable object.

Classes that require special handling during the serialization and deserialization process must implement special methods with these exact signatures:

private void writeObject(java.io.ObjectOutputStream out) throws IOException private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException; private void readObjectNoData() throws ObjectStreamException;

The writeObject method is responsible for writing the state of the object for its particular class so that the corresponding readObject method can restore it. The default mechanism for saving the Object’s fields can be invoked by calling out.defaultWriteObject. The method does not need to concern itself with the state belonging to its superclasses or subclasses. State is saved by writing the individual fields to the ObjectOutputStream using the writeObject method or by using the methods for primitive data types supported by DataOutput.

The readObject method is responsible for reading from the stream and restoring the classes fields. It may call in.defaultReadObject to invoke the default mechanism for restoring the object’s non-static and non-transient fields. The defaultReadObject method uses information in the stream to assign the fields of the object saved in the stream with the correspondingly named fields in the current object. This handles the case when the class has evolved to add new fields. The method does not need to concern itself with the state belonging to its superclasses or subclasses. State is restored by reading data from the ObjectInputStream for the individual fields and making assignments to the appropriate fields of the object. Reading primitive data types is supported by DataInput.

Читайте также:  Stream to string cpp

The readObjectNoData method is responsible for initializing 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. 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 been tampered; hence, readObjectNoData is useful for initializing deserialized objects properly despite a «hostile» or incomplete source stream.

Serializable classes that need to designate an alternative object to be used when writing an object to the stream should implement this special method with the exact signature:

ANY-ACCESS-MODIFIER Object writeReplace() throws ObjectStreamException;

This writeReplace method is invoked by serialization if the method exists and it would be accessible from a method defined within the class of the object being serialized. Thus, the method can have private, protected and package-private access. Subclass access to this method follows java accessibility rules.

Classes that need to designate a replacement when an instance of it is read from the stream should implement this special method with the exact signature.

ANY-ACCESS-MODIFIER Object readResolve() throws ObjectStreamException;

This readResolve method follows the same invocation rules and accessibility rules as writeReplace.

Enum types are all serializable and receive treatment defined by the Java Object Serialization Specification during serialization and deserialization. Any declarations of the special handling methods discussed above are ignored for enum types.

Record classes can implement Serializable and receive treatment defined by the Java Object Serialization Specification, Section 1.13, «Serialization of Records». Any declarations of the special handling methods discussed above are ignored for record types.

The serialization runtime associates with each serializable class a version number, called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. If the receiver has loaded a class for the object that has a different serialVersionUID than that of the corresponding sender’s class, then deserialization will result in an InvalidClassException . A serializable class can declare its own serialVersionUID explicitly by declaring a field named «serialVersionUID» that must be static, final, and of type long :

ANY-ACCESS-MODIFIER static final long serialVersionUID = 42L;

If a serializable class does not explicitly declare a serialVersionUID, then the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class, as described in the Java Object Serialization Specification. This specification defines the serialVersionUID of an enum type to be 0L. However, it is strongly recommended that all serializable classes other than enum types explicitly declare serialVersionUID values, since the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected InvalidClassException s during deserialization. Therefore, to guarantee a consistent serialVersionUID value across different java compiler implementations, a serializable class must declare an explicit serialVersionUID value. It is also strongly advised that explicit serialVersionUID declarations use the private modifier where possible, since such declarations apply only to the immediately declaring class—serialVersionUID fields are not useful as inherited members. Array classes cannot declare an explicit serialVersionUID, so they always have the default computed value, but the requirement for matching serialVersionUID values is waived for array classes.

Читайте также:  Post запрос python примеры

Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples. Other versions.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2023, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.

Источник

How To Serialize And Deserialize Interfaces In Java Using Gson

Technology

Gson is a Java Library widely used to convert Java Objects into their JSON representation and vice versa.

Getting Started

Let’s start by creating a new Java project. We can call it «InterfaceSerialization».

We need to add the gson library in our project in order for us to use it. If you are using Maven, add the latest version of gson to the POM file.

 com.google.code.gson gson 2.3.1  

Step 1:

Now, let’s create our Java interface. This time I will be using «Cars» as an example. I love cars, who doesn’t?

Our interface declares three features that all cars share.

Step 2:

Let’s now create our Java classes that will implement our «Car» interface. I will be using «Lexus» and «Acura» (my favorite brands) for this example.

Let’s define our Lexus class:

public class Lexus implements Car < private int maxSpeed; private String type; private int rankingAmongSedans; private String model; public Lexus(String model, int maxSpeed, String type, int rankingAmongSedans) < this.model = model; this.maxSpeed = maxSpeed; this.type = type; this.rankingAmongSedans = rankingAmongSedans; >public String model() < return model; >public int maxSpeed() < return maxSpeed; >public String type() < return type; >public int getRankingAmongSedans() < return rankingAmongSedans; >@Override public String toString() < return "Model: " + model + ", Max speed: " + maxSpeed + " km/h, Type: " + type + ", Ranking: " + rankingAmongSedans ; >>

Step 3:

In the same way we have to define our Acura class

public class Acura implements Car < private int maxSpeed; private String type; private String model; public Acura(String model, int maxSpeed, String type) < this.model = model; this.maxSpeed = maxSpeed; this.type = type; >public String model() < return null; >public int maxSpeed() < return maxSpeed; >public String type() < return type; >@Override public String toString() < return "Model: " + model + ", Max speed: " + maxSpeed + " km/h, Type: " + type; >>

Notice that the Lexus class contains an extra field called «rankingAmongSedans». This will help us to distinguish between the two and prove that our serialization works properly.

Step 4:

Now let’s define our test class:

public class Test < public static void main(String[] args) < //Let's initialize our sample array of cars Car cars[] = new Car[]; //Create our gson instance Gson gson = new Gson(); //Let's serialize our array String carsJsonFormat = gson.toJson(cars, Car[].class); //Let's Print our serialized arrya System.out.println("Cars in Json Format: " + carsJsonFormat); > >

In this class, we are basically creating an array of «Cars» with two car objects, one being of Class Type Lexus, and the other one of Class Type Acura

Читайте также:  Wing ide python path

Then we instantiate a gson object called “Gson” and proceed to serialize our array. Finally we print our array in JSON format.

Our output should look like this:

It seems that everything went fine, our array of cars is printed in JSON format; however, what happens when we try to deserialize the String back to an array of Car Objects?

Let’s add this line code after our print statement and try to re run our test again.

Car [] carJsonArray = gson.fromJson(carsJsonFormat, Car[].class);

Oops, did you get this? RunTimeException: «Unable to invoke no-args constructor for interface Car. Register an InstanceCreator with Gson for this type may fix this problem.»

JSON Serialize

Gson doesn’t have way to identify which «Car Object» we are trying to deserialize. We need to register a Type Adapter that will help gson differentiate the objects.

Step 5: (The solution)

So let’s define a Generic Interface Adapter (so we are not only restricted to our car interface) that will override serialize and deserialize methods.

The magic happens in this class, as we define a mapping structure to distinguish our Car Objects, where «CLASSNAME» is the key to get the object’s class name, and «DATA» is the key that maps the actual JSON object.

public class InterfaceAdapter implements JsonSerializer, JsonDeserializer < private static final String CLASSNAME = "CLASSNAME"; private static final String DATA = "DATA"; public T deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException < JsonObject jsonObject = jsonElement.getAsJsonObject(); JsonPrimitive prim = (JsonPrimitive) jsonObject.get(CLASSNAME); String className = prim.getAsString(); Class klass = getObjectClass(className); return jsonDeserializationContext.deserialize(jsonObject.get(DATA), klass); >public JsonElement serialize(T jsonElement, Type type, JsonSerializationContext jsonSerializationContext) < JsonObject jsonObject = new JsonObject(); jsonObject.addProperty(CLASSNAME, jsonElement.getClass().getName()); jsonObject.add(DATA, jsonSerializationContext.serialize(jsonElement)); return jsonObject; >/****** Helper method to get the className of the object to be deserialized *****/ public Class getObjectClass(String className) < try < return Class.forName(className); >catch (ClassNotFoundException e) < //e.printStackTrace(); throw new JsonParseException(e.getMessage()); >> > > 

Step 6:

Now, let’s go back to our test class and add the registerTypeAdapter to our gson object. Since we are using a customized gson object, we need to construct it with «gsonBuilder».

Let’s replace Gson gson = new Gson(); with:

//Create our gson instance GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(Car.class, new InterfaceAdapter()); Gson gson = builder.create(); 

Now that we have registered our InterfaceAdapter, we’ll add these lines of code to print our results:

//Let's print our car objects to verify System.out.println("\n**********************************************************************"); System.out.println("My favorite Cars of 2015"); for(Car aCar : carJsonArray) < System.out.println(aCar); >System.out.println("**********************************************************************");

Let’s test again and see what happens. After running our test class, we should see the following output: Cars in JSON Format:

Model: Lexus Is, Max speed: 260 km/h, Type: Sedan, Ranking: 3

Model: Acura Mdx, Max speed: 193 km/h, Type: Suv

We were able to achieve our goal using gson by just adding an interface adapter. It’s up to you how to customize the serialization of different data types.

Источник

Оцените статью