简体   繁体   中英

How does Java define or detect a class as a serializable class?

I was working with a class extending a Swing Object Class (eg public myClass extends JFrame ) and with methods/variables referring to Screen objects/DisplayMode/Graphics .

There were no issues. However when I tried to cast Grphics instance g to a Graphics2D object, I have gotten, seem-to-be-common error as explained in multiple places of SE with great answers and information .

I AM CURIOUS! Because I managed to solve the issue without adding a serialVersionID or without implementing serializable interface. And as said I don't need my class to be serialized. Since it was solved without having to implement/extend serializable interface or adding serialVersionID - I am just curious to understand in what scenarios compiler decides or treats a class as or better be serialized...I am not sure how else I can explain this.

What I want to know, how/under what criteria does Java Compiler qualify a class as a serializable and demand a Serial ID? In my case neither I required a serialization nor did I specify one.

class SerializableClass implements Serializable

You just implement the interface. Java never demands a Serial ID; if you don't provide one it's determined at runtime.

You can also extend a serializable class:

class AnotherSerializableClass extends SerializableClass

Java classifies a class as Serializable if it either implements Serializable itself or extends a class which implements Serializable.

Since MyClass extends JFrame which implements Serializable , your class is serializable.

There are two cases.

  1. The class isn't compiled and contains 'implements Serializable'.
  2. The class is compiled, and therefore loadable, and 'Serializable.class.isAssignableFrom(thisClass)' returns true, where 'thisClass' is the result of loading the class.

(3) Repeat for all the base classes.

Note that this is the IDE doing this, not the Java compiler. It's not a compile error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM