1

我有一个类叫Packet和一个叫PacketClientConnecting女巫的类扩展它。的实例PacketClientConnecting和其他数据包存储在ArrayList<Packet>.

我想以staticnon-static方式访问 id 值,例如PacketClientConnecting.getStaticId()or packetArrayList.get(5).getId()

如何在不覆盖每个类中的两个函数的情况下做到这一点?

4

1 回答 1

0

我不认为有一种非常流畅的方法可以做到这一点,但是可以通过使用反射来实现你想要的(只有一次:在基类中):

class Packet {

    public static int getStaticId() {
        return 1;
    }

    // This method is virtual and will be inherited without change
    public int getId() {
        try {
            // Find and invoke the static method corresponding 
            // to the run-time instance
            Method getStaticId = this.getClass().getMethod("getStaticId");
            return (Integer) getStaticId.invoke(null);

        // Catch three reflection-related exceptions at once, if you are on Java 7+,
        // use multi-catch or just ReflectiveOperationException
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }
}

现在在子类中,您只需要定义 getStaticId():

class PacketClientConnecting extends Packet {
    public static int getStaticId() {
        return 2;
    }
}

让我们测试一下:

class Main {
    public static void main(String[] args) {
        // Both print 1
        System.out.println(Packet.getStaticId());
        System.out.println(new Packet().getId());

        // Both print 2
        System.out.println(PacketClientConnecting.getStaticId());
        System.out.println(new PacketClientConnecting().getId());
    }
}

如果要避免每次调用 getId() 时调用反射操作的开销,可以使用基类中的字段来缓存 id:

class Packet {

    public static int getStaticId() {
        return 1;
    }

    private final int id = computeId();

    public int getId() {
        return id;
    }

    // This method runs once per instance created
    private int computeId() {
        try {
            Method getStaticId = this.getClass().getMethod("getStaticId");
            return (Integer) getStaticId.invoke(null);
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }
}
于 2013-11-23T06:12:50.720 回答