Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Java annotations serializable?

The Java Annotation interface does not extend Serializable. However, Java annotation values are serializable (implemented using java.lang.reflect.Proxy, with a serializable invocation handler).

Is this guaranteed anywhere? My search-foo is failing to find a reference. Or if I need to serialize annotation instances safely, do I need to create my own serialization proxies?

like image 231
Michael Ekstrand Avatar asked Apr 09 '13 14:04

Michael Ekstrand


People also ask

Are Java strings serializable?

The String class and all the wrapper classes implement the java. io. Serializable interface by default.

Which Java classes are not serializable?

io. Serializable interface. This is only a marker interface which tells the Java platform that the object is serializable. Certain system-level classes such as Thread , OutputStream and its subclasses, and Socket are not serializable.

Are all Java objects serializable?

A Java object is serializable if its class or any of its superclasses implements either the java. io. Serializable interface or its subinterface, java.

Are Java records serializable?

Serialization with records With Java Serialization, a record class is made serializable just like a normal class, simply by implementing java. io.


2 Answers

Annotation objects returned by methods of java.lang.reflect.AnnotatedElement are Serializable. This is what API says: This interface allows annotations to be read reflectively. All annotations returned by methods in this interface are immutable and serializable.

All classes capable of returning annotation objects (Class, Constructor, Field, Method, Package, Parameter) implement AnnotatedElement and are obliged to create / return Serializable objects by the above contract.

like image 56
Evgeniy Dorofeev Avatar answered Sep 19 '22 03:09

Evgeniy Dorofeev


Annotations are part of the class definition, and thus would never be written to a serialization stream (at least not with standard java serialization) when serializing an instance of a class which has annotations.

UPDATE: I guess i missed the point of the original question which was referring to specifically serializing an instance of an actual Annotation.

like image 31
jtahlborn Avatar answered Sep 20 '22 03:09

jtahlborn