简体   繁体   中英

Kryonet — How can I register classes within my class?

I have the following class:

public class QueryResults {
    protected Set<String> resultList = new HashSet<String>();
    protected long executionTime = 0;

    public long getExecutionTime() { return executionTime; }
    [...]
}

And I register it as so:

Registrar.RegisterClass(this, QueryResults.class);
------------
public class Registrar {
    public static void RegisterClass(Node n, Class theClass) {
        Map<String, Node> nodeMap = Node.getNodeMap();
        for (Map.Entry<String, Node> node : nodeMap.entrySet()) {
            if (node.getKey().equals(n.getHostname())) {
                Log.info("Registering " + theClass.getSimpleName() + " for " + node.getValue().getHostname());
                node.getValue().getServer().getConnection().getKryo().register(theClass);
                node.getValue().getClient().getConnection().getKryo().register(theClass);
            }
        }
    }
}

This has worked well until attempting to serialize QueryResults , due to it containing a container, in this case a HashSet (We've tried an ArrayList as well, with the same results).

On the endpoint populating and ultimately serializing this class to send back to the caller, I get this output:

 Exception in thread "Server" com.esotericsoftware.kryo.KryoException: java.lang.IllegalArgumentException: Class is not registered: java.util.HashSet Note: To register this class use: kryo.register(java.util.HashSet.class); 

If I explicitly call Registrar.RegisterClass(this, HashSet.class); , everything works swimmingly. However, this can be annoying once we start to implement more advanced classes, with many types of containers.

Am I doing something wrong?

How about using kryo bind annotations :

public class QueryResults {

    @CollectionSerializer.BindCollection(
         elementClass = QueryResults.class,
         elementSerializer = DefaultSerializers.StringSerializer.class) 
    protected Set<String> resultList = new HashSet<String>();

    ...
}

Also check a set of additional kryo serialisers .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM