Can a class annotation affect its default serialization? Java docs say
Annotations do not directly affect program semantics, but they do affect the way programs are treated by tools and libraries, which can in turn affect the semantics of the running program. Annotations can be read from source files, class files, or reflectively at run time.
This would lead me to guess no, but I have not found a conclusive statement.
Edit: I meant to ask “Can an annotation affect Java default serialization?” So, I am changing the question text and accepting the less popular answer. My apologies to the person who answered what I asked previously (“Can an annotation affect serialization?”). 🙂 Yes, you can construct cases that affect serialization. However, I think the changed question will be of more practical value, certainly to me.
Annotations with
RETENTION=RUNTIMEare in byte code, but not serialized themselves. Serialization works with object fields, not with classes.Annotations can be used by serializer. However, the standard java serialization mechanism does not use them: it was created for java 1.0, 10 years before annotations.
However, custom mechanisms can use annotations. For example, you can create a
@Transientannotation and use it to mark fields that should not be serialized.Serialization can be customized using a
writeObject()method or with a third party library like xstream.There are a lot of serialization libraries. You can think about JAXB or XStream as libraries that serialize object to XML. Both support a large set of annotations.