@@ -28,7 +28,7 @@ public static HypixelModAPI getInstance() {
2828 }
2929
3030 private final PacketRegistry registry = new PacketRegistry ();
31- private final List < ClientboundPacketHandler > handlers = new CopyOnWriteArrayList <>();
31+ private final Map < Class <? extends ClientboundHypixelPacket >, Collection < ClientboundPacketHandler <?>>> handlers = new ConcurrentHashMap <>();
3232 private final Set <String > subscribedEvents = ConcurrentHashMap .newKeySet ();
3333 private Set <String > lastSubscribedEvents = Collections .emptySet ();
3434 private Predicate <HypixelPacket > packetSender = null ;
@@ -71,20 +71,16 @@ private void registerEventPackets() {
7171 }
7272
7373 private void registerDefaultHandler () {
74- registerHandler (new ClientboundPacketHandler () {
75- @ Override
76- public void onHelloEvent (ClientboundHelloPacket packet ) {
77- sendRegisterPacket (true );
78- }
79- });
74+ registerHandler (ClientboundHelloPacket .class , p -> sendRegisterPacket (true ));
8075 }
8176
8277 public PacketRegistry getRegistry () {
8378 return registry ;
8479 }
8580
86- public void registerHandler (ClientboundPacketHandler handler ) {
87- handlers .add (handler );
81+ public <T extends ClientboundHypixelPacket > void registerHandler (Class <T > packetClass , ClientboundPacketHandler <T > handler ) {
82+ if (packetClass == null || handler == null ) return ;
83+ handlers .computeIfAbsent (packetClass , cls -> new CopyOnWriteArrayList <>()).add (handler );
8884 }
8985
9086 public void subscribeToEventPacket (Class <? extends EventPacket > packet ) {
@@ -134,9 +130,14 @@ public void handle(String identifier, PacketSerializer serializer) {
134130 handle (packet );
135131 }
136132
133+ @ SuppressWarnings ("unchecked" )
137134 public void handle (ClientboundHypixelPacket packet ) {
138- for (ClientboundPacketHandler handler : handlers ) {
139- packet .handle (handler );
135+ Collection <ClientboundPacketHandler <?>> typedHandlers = handlers .get (packet .getClass ());
136+ // nothing registered for this packet.
137+ if (typedHandlers == null ) return ;
138+ for (ClientboundPacketHandler <?> handler : typedHandlers ) {
139+ // this cast is safe as we ensure its type when it is added to the handlers list in the first place.
140+ ((ClientboundPacketHandler <ClientboundHypixelPacket >) handler ).handle (packet );
140141 }
141142 }
142143
0 commit comments