Function pointers/delegates in Java?

前端 未结 10 1468
有刺的猬
有刺的猬 2020-12-15 21:06

For my Java game server I send the Action ID of the packet which basically tells the server what the packet is for. I want to map each Action ID (an integer) to a function.

10条回答
  •  鱼传尺愫
    2020-12-15 21:38

    Java does not have first-class function pointers. In order to achieve similar functionality, you have to define and implement an interface. You can make it easier using anonymous inner classes, but it's still not very pretty. Here's an example:

    public interface PacketProcessor
    {
        public void processPacket(Packet packet);
    }
    
    ...
    
    PacketProcessor doThing1 = new PacketProcessor()
    {
        public void processPacket(Packet packet)
        {
            // do thing 1
        }
    };
    // etc.
    
    // Now doThing1, doThing2 can be used like function pointers for a function taking a
    // Packet and returning void
    

提交回复
热议问题