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.
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.
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.
Explanation: writeObject() and readObject() methods should be implemented to avoid Java serialization.
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.
Make your classes implement Externalizable, then ObjectOuputStream.writeObject() / readObject() will invoke writeExternal(ObjectOutput out) / readExternal(ObjectInput) on your objects directy, without using reflection
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With