Friday, April 26, 2024
HomeJavaQuiz your self: Deserialization of Java enum varieties and data

Quiz your self: Deserialization of Java enum varieties and data


Think about you’re given the next enum and document:

Quiz Yourself, Deserialization of Java Enum, Java Career, Java Skill, Java Tutorial and Materials, Java Job, Java Learning, Java Guides

enum Gender {

  MALE(“M”), FEMALE(“F”), OTHER;

  Gender() {

    System.out.print(“Gender “);

  }

  Gender(String s) {

    System.out.print(“GenderS “);

  }

}

document Particular person(int age, String identify, Gender g) implements Serializable {

  Particular person() {

    this(0, “”, Gender.OTHER);

    System.out.print(“Particular person “);

  }

  Particular person {

    System.out.print(“PersonC “);

  }

}

Beforehand an occasion of Particular person was constructed like the next and serialized to a file:

var v = new Particular person(60, “John Doe”, Gender.MALE);

What is perhaps printed to the console when a program deserializes the contents of the file talked about above? Select two.

A. Gender PersonC Particular person

B. Gender PersonC

C. PersonC Particular person

D. PersonC

E. Gender Gender Gender Particular person PersonC

F. GenderS GenderS Gender Particular person PersonC

G. GenderS GenderS Gender PersonC

Reply. This query investigates the mechanisms of deserialization for each enum varieties and data.

When a document is deserialized, every of the attributes—on this case the age, identify, and gender attributes—should be deserialized to their respective objects or values first. (Word that the age primitive won’t create an object.) These attributes are then handed to the canonical constructor of the document. Word that this habits with data is sort of completely different from deserializing situations of regular lessons. No output is printed in dealing with the int age and the String identify attributes, however it’s attainable that output is perhaps printed for Gender. You must have a look at this primary.

At any time when code working in a JVM refers to a selected enum worth, execution can not proceed except that enum worth has been initialized. Typically, the very first reference to considered one of these values would require a number of steps to be carried out: class loading, class linking, and sophistication preparation. These three steps should occur within the order listed.

It’s pretty uncommon for builders to note the truth that these steps are separate, however that actually doesn’t matter. Class preparation is the step that performs static initialization, and subsequently it’s the step that creates the values of the enum itself. This quiz query is unaffected by the sooner steps, so the next dialogue will take into account the enum to be totally ready, ignoring the truth that that’s really the final of a number of steps. (Should you’re on this, you will discover extra in part 12.2 and part 12.3 of the Java Language Specification, which in flip seek advice from the Java Digital Machine Specification.)

For this query, you should know three issues.

◉ An try and deserialize an object that incorporates a area of an enum kind will make a reference to an enum worth.

◉ Any reference to an enum worth requires the enum class to be totally ready.

◉ Subsequently, the enum should have been totally ready—full with the initialization of all of the enum’s constants—earlier than deserialization can proceed.

In view of the above, there at the moment are two distinct prospects.

First, suppose that for the time being when an occasion of Particular person is deserialized, the enum has not been totally ready. On this case, it will likely be essential to carry out that preparation earlier than Particular person can proceed with deserialization. That initialization consists of instantiating all three of the enum’s values. On this state of affairs, count on the three situations to be initialized utilizing their acceptable constructors. (Keep in mind that is the initialization course of, not deserialization itself, that’s inflicting this habits.) So, on this state of affairs, you will note GenderS GenderS Gender because the output, previous any output referring to Particular person.

In contrast, if the Gender kind has been totally ready earlier than the second when an occasion of Particular person is deserialized, the three situations exist already, and no additional constructor habits can be invoked for the Gender kind. In such a state of affairs, no messages associated to Gender can be output by the deserialization course of.

As soon as the enum is totally ready, deserialization of the document kind can proceed; word that document varieties differ from different lessons in how this occurs. A selected distinction is that the canonical constructor for a document kind is invoked to carry out the initialization of the newly allotted object. In contrast, common serializable lessons don’t have any constructor invoked, neither is any of the conventional occasion initialization of the serializable class itself run. (Word, nevertheless, that nonserializable mum or dad varieties can have their default constructors executed throughout deserialization.)

Provided that the canonical constructor is invoked, you will note the message PersonC printed as output. Word that on this case, the canonical constructor is offered within the compact type whereas the argument checklist is omitted, as is the code that initializes the fields of the document.

Since you may or won’t see GenderS GenderS Gender, and you will note PersonC within the output, the 2 legitimate solutions are

PersonC

GenderS GenderS Gender PersonC

These match choices D and G, which tells you that these are the proper choices and, by elimination, the opposite choices are incorrect.

If you wish to dive extra deeply into the serialization course of, it’s, in fact, within the Java specification. See the part that describes the course of because it pertains to data. Specifically, the documentation notes the next:

Throughout deserialization, if the native class equal of the required stream class descriptor is a document class, then first the stream fields are learn and reconstructed to function the document’s element values; and second, a document object is created by invoking the document’s canonical constructor with the element values as arguments…

To deserialize an enum fixed, ObjectInputStream reads the fixed identify from the stream; the deserialized fixed is then obtained by calling the java.lang.Enum.valueOf technique, passing the fixed’s enum kind together with the acquired fixed identify as arguments.

Discover that the enum deserialization course of doesn’t instantiate the values of the enum except, by necessity, the static initialization course of should be accomplished to finish the deserialization.

As a aspect word, the descriptions above touched on the concept that there are a number of steps on the best way to class preparation. Most JVMs will carry out these steps lazily, merely guaranteeing {that a} class is ready earlier than it’s really wanted. The precise particulars can fluctuate from one JVM to the subsequent even when the habits of the developer’s code conforms to the expectations listed within the Java specification.

This lazy method will be fairly helpful. For instance, take into account a program with a assist system that’s constructed with many lessons which are distinctive to it. If the assistance system is rarely used throughout an execution of that program, these lessons won’t be wanted, they usually may by no means be loaded in any respect. Additional, even when a category is loaded, it won’t have to be ready. Both of those conditions can save reminiscence.

To see how this works, attempt constructing the next code and observing at what level within the course of the MyLazySingleton class is ready. (Do not forget that preparation pertains to the static initialization.)

class MyLazySingleton {

  static {

    System.out.println(“making ready MyLazySingleton”);

  }

  personal static ultimate MyLazySingleton singleton =

    new MyLazySingleton();

  personal MyLazySingleton() {

    System.out.println(“instantiating MyLazySingleton”);

  }

  public static MyLazySingleton get() {

    return singleton;

  }

}

public class TryStuff {

  public static void most important(String[] args) {

    System.out.println(“Beginning”);

    MyLazySingleton mls = null;

    System.out.println(“mls variable initialized to null”);

    Class<?> cl = MyLazySingleton.class;

    System.out.println(“MyLazySingleton.class evaluated.”);

    mls = MyLazySingleton.get();

    System.out.println(“singleton retrieved”);

  }

}

Should you run this code below a tracing instrument, you’ll most likely discover that the file myclasspath/packagename/MyLazySingleton.class is learn in the course of the reference to the java.lang.Class object MyLazySingleton.class. Nonetheless, you’ll additionally see that the static initialization and, with it, the instantiation of the one occasion of MyLazySingleton, doesn’t happen till the code invokes MyLazySingleton.get().

Conclusion. The proper solutions are choices D and G.

Supply: oracle.com

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments