简体   繁体   English

如何自动将所有嵌套的静态类作为参数传递给方法调用?

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

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 ? 有没有办法在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());
        }
    }
}

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: 如果对getDeclaredClasses()调用的结果使用了正确的类型,则将更加明显:

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

(btw, you are already using reflection -> getDeclaredClasses() ). (顺便说一句,您已经在使用反射-> getDeclaredClasses() )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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