How do you automatically pass all nested static classes into a method call as a parameter?

119 views Asked by At

Is there a way of retrieving an array of static classes within the Network class (defined below), and pass each class's attribute class into a parameter of a method call 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());
        }
    }
}
1

There are 1 answers

0
jtahlborn On BEST ANSWER

The problem is that you are using the class of the class, which isn't what you want. if you used the correct type for the result of the getDeclaredClasses() call, it would have been more obvious:

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

(btw, you are already using reflection -> getDeclaredClasses()).