Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do Java serialization without Reflection?

I am working on a Lego Mindstorm NXT robot, which do not support Java reflection.

For some reason (the parallel creation of a simulator and an actual mindstorm) we want to use Serialization to exchange Java objects.

The problem is that serialization uses reflection, which the JVM on the mindstorm does not support.

Any ideas?

I found this page on Zwong.de, but the source code has been removed.

like image 412
Steven Roose Avatar asked Mar 05 '13 13:03

Steven Roose


People also ask

Does Java serialization use reflection?

Java serialization uses reflection to scrape all necessary data from the object's fields, including private and final fields. If a field contains an object, that object is serialized recursively. Even though you might have getters and setters, these functions are not used when serializing an object in Java.

How do you stop a reflection in Java?

Overcome reflection issue: To overcome issue raised by reflection, enums are used because java ensures internally that enum value is instantiated only once. Since java Enums are globally accessible, they can be used for singletons. Its only drawback is that it is not flexible i.e it does not allow lazy initialization.

Is there any other method to avoid serialization?

Explanation: writeObject() and readObject() methods should be implemented to avoid Java serialization.

How do you avoid variables to serialize?

You can prevent member variables from being serialized by marking them with the NonSerialized attribute as follows. If possible, make an object that could contain security-sensitive data nonserializable. If the object must be serialized, apply the NonSerialized attribute to specific fields that store sensitive data.


2 Answers

Make your classes implement Externalizable, then ObjectOuputStream.writeObject() / readObject() will invoke writeExternal(ObjectOutput out) / readExternal(ObjectInput) on your objects directy, without using reflection

like image 91
Evgeniy Dorofeev Avatar answered Sep 21 '22 05:09

Evgeniy Dorofeev


I believe Kryo supports reflection-less instantiation of serializable objects. A quick look on their home page seems to confirm it:

When ReflectASM or reflection cannot be used, Kryo can be configured to use an InstantiatorStrategy to handle creating instances of a class. Objenesis provides StdInstantiatorStrategy which uses JVM specific APIs to create an instance of a class without calling any constructor at all. This works on many JVMs.

It sounds from that like you'll need to create your own InstantiatorStrategy, since I'm not sure the standard one will have support for the NXT JVM - worth a try though! I haven't tried this myself, but it sounds like it should be possible in theory.

like image 34
Michael Berry Avatar answered Sep 20 '22 05:09

Michael Berry