-
Notifications
You must be signed in to change notification settings - Fork 1
/
EventSender.java
76 lines (65 loc) · 2.24 KB
/
EventSender.java
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package arclibrary.utils.events;
import arc.*;
import arc.struct.*;
import arc.util.*;
import lombok.*;
import org.jetbrains.annotations.*;
import java.lang.reflect.*;
import java.util.*;
public class EventSender<T>{
public final String commandName;
public final EventSignature<T> signature;
private final ObjectMap<String, Object> parametersMap = new ObjectMap<>();
public EventSender(EventReceiver<T> receiver){
this(receiver.commandName, receiver.signature);
}
public EventSender(String commandName, @NotNull EventSignature<T> signature){
this.commandName = commandName;
this.signature = Objects.requireNonNull(signature);
}
public static <T> EventSender<T> from(EventReceiver<T> sender){
return new EventSender<>(sender);
}
public <P> void setParameter(String name, P parameter){
parametersMap.put(name, parameter);
}
@SuppressWarnings("unused")
@SneakyThrows
public void setParameters(@NotNull T object){
Objects.requireNonNull(object, "object cannot be null");
//noinspection UnnecessaryLocalVariable
Class<T> signatureClass = signature.targetClass();
Class<?> c = signatureClass;
while(c != null){
Field[] fields = c.getDeclaredFields();
for(Field field : fields){
int modifiers = field.getModifiers();
if(!Modifier.isPublic(modifiers) || Modifier.isStatic(modifiers)) continue;
field.setAccessible(true);
setParameter(field.getName(), field.get(object));
}
c = c.getSuperclass();
}
}
public void clear(){
parametersMap.clear();
}
public void fire(){
fire(false);
}
public void fire(boolean clearParams){
Seq<Object> objects = new Seq<>();
objects.add(commandName);
if(signature != null){
objects.add(EventSignature.eventSignatureParam);
objects.add((Object)signature.toObjects());
}
for(ObjectMap.Entry<String, Object> entry : parametersMap){
objects.add(entry.key, entry.value);
}
Events.fire(objects.toArray(Object.class));
if(clearParams){
clear();
}
}
}