0

有没有办法在类中检索静态类数组Network(定义如下),并将每个类的属性传递class给方法调用的参数kryo.register

public class Network {
    // Classes to be transferred between the client and the server
    public static class A {
        public int id;
        public String name;
    }

    public static class B {
        public int id;
        public int x;
        public int y;
    }

    // Rest of the classes are defined over here

    static public void register(EndPoint endPoint) {
        Kryo kryo = endPoint.getKryo();

        // typical way of registering classes so that kryonet can use it
        // kryo.register(A.class);
        // kryo.register(B.class);
        // the rest of the classes are registered with kryonet over here

        // my attempt at solving the question,
        // but for some reason this doesn't work?
        for(Object o : Network.class.getDeclaredClasses()) {
            kryo.register(o.getClass());
        }
    }
}
4

1 回答 1

1

问题是您正在使用该类的类,这不是您想要的。如果您对getDeclaredClasses()调用结果使用正确的类型,那将更加明显:

    for(Class<?> c : Network.class.getDeclaredClasses()) {
        kryo.register(c);
    }

(顺便说一句,您已经在使用反射 -> getDeclaredClasses())。

于 2014-12-21T02:32:17.693 回答