18045010223
2025-07-07 0d3a683a0c97154b1f2e6657398664537e4e3e82
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package org.yzh.client.netty;
 
import io.github.yezhihao.netmc.core.annotation.Endpoint;
import io.github.yezhihao.netmc.core.annotation.Mapping;
import io.github.yezhihao.netmc.util.ClassUtils;
import lombok.SneakyThrows;
 
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
public class HandlerMapping {
 
    private final Map<Integer, Handler> handlerMap = new HashMap<>(55);
 
    public HandlerMapping(String... packageNames) {
        for (String packageName : packageNames) {
            initial(packageName);
        }
    }
 
    private void initial(String packageName) {
        List<Class> handlerClassList = ClassUtils.getClassList(packageName, Endpoint.class);
 
        for (Class handlerClass : handlerClassList) {
            Method[] methods = handlerClass.getDeclaredMethods();
 
            for (Method method : methods) {
                if (method.isAnnotationPresent(Mapping.class)) {
                    Mapping annotation = method.getAnnotation(Mapping.class);
                    String desc = annotation.desc();
                    int[] types = annotation.types();
                    Handler value = new Handler(newInstance(handlerClass), method, desc);
                    for (int type : types) {
                        handlerMap.put(type, value);
                    }
                }
            }
        }
    }
 
    @SneakyThrows
    private Object newInstance(Class handlerClass) {
        return handlerClass.newInstance();
    }
 
    public Handler getHandler(int messageId) {
        return handlerMap.get(messageId);
    }
 
}