junkdog / artemis-odb

A continuation of the popular Artemis ECS framework
BSD 2-Clause "Simplified" License
776 stars 111 forks source link

Error with Serialization of EnumMap #564

Closed mguldner closed 5 years ago

mguldner commented 5 years ago

Hello,

I'm working on a project using artemis-odb. I started to work on the serialization part but I've got this error :

com.badlogic.gdx.utils.SerializationException: Class cannot be created (missing no-arg constructor): java.util.EnumMap

This error is caused by :

Caused by: java.lang.NoSuchMethodException: java.util.EnumMap.init () at java.base/java.lang.Class.getConstructor0(Class.java:3302) at java.base/java.lang.Class.newInstance(Class.java:532)

I receive this error when I try to serialize a Component with an instance variable of type EnumMap. It seems that, because no constructor exists for EnumMap with no arguments, the serialization process can't work because using Reflection.

Is there a way to make it work ?

PS : I found this related issue in Kryo project : https://github.com/EsotericSoftware/kryo/issues/488

junkdog commented 5 years ago

Hi :wave:

Yeah, the default serializer can only cope with no-arg constructors, so you need to provide a component-specific serializer. The serializer backends - json, json-libgdx and kryo - each provide a register(class, serializer) method for this purpose. so for the libgdx JsonArtemisSerializer, something like:

serializer.register(Position.class, new Json.Serializer<Position>() {
    @Override
    public void write(Json json, Position object, Class knownType) {

    }

    @Override
    public Position read(Json json, JsonValue jsonData, Class type) {
        return null;
    }
});
mguldner commented 5 years ago

Ok ! Thanks for your answer, I'll try to make it work! :)

junkdog commented 5 years ago

Nice, closing this for now then :)

mguldner commented 5 years ago

I implemented what you proposed for a generic object of type EnumMap<T, U> (T and U being serializable objects according to artemis-odb). Could it be useful to create a MR whit that ?

junkdog commented 5 years ago

Could it be useful to create a MR whit that ?

Cool! Please do :)