Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can an annotation affect the Java default serialization?

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.

like image 605
dfrankow Avatar asked Jul 18 '26 17:07

dfrankow


2 Answers

It is possible to construct a class that serializes differently based on runtime annotations.

public class Foo implements Externalizable {
  public void writeExternal(ObjectOutputStream out) throws IOException {
    if (getClass().getAnnotations().length == 0) {
      out.writeObject("no");
    } else {
      out.writeObject("yes");
    }
  }
  public void readExternal(ObjectInputStream in) throws IOException { ... }
}

and then instances of a subclass that has a runtime annotation would serialize differently from the parent class despite the fact that the writeExternal is shared.

@Retention(RetentionPolicy.RUNTIME)
@interface ARuntimeAnnotation {}

@ARuntimeAnnotation
public class SubFoo extends Foo {}

This happens because annotations with RetentionPolicy.RUNTIME "can in turn affect the semantics of the running program" as you quoted.

like image 191
Mike Samuel Avatar answered Jul 20 '26 05:07

Mike Samuel


Annotations with RETENTION=RUNTIME are 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 @Transient annotation 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.

like image 30
AlexR Avatar answered Jul 20 '26 06:07

AlexR