Skip to content

Commit 832410e

Browse files
committed
Added @ModuleInstance annotation. Annotate a static field inside your module class to have it populated with its instance, allowing for easy singleton patterns. This is opt in
1 parent ccac3d9 commit 832410e

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
package org.violetmoon.zeta.module;
2+
3+
import java.lang.annotation.ElementType;
4+
import java.lang.annotation.Retention;
5+
import java.lang.annotation.RetentionPolicy;
6+
import java.lang.annotation.Target;
7+
8+
// populates a public static field in your module class with the module instance. Needs to be inside a @ZetaLoadModule class
9+
@Retention(RetentionPolicy.RUNTIME)
10+
@Target(ElementType.FIELD)
11+
public @interface ModuleInstance {
12+
13+
}

src/main/java/org/violetmoon/zeta/module/ZetaModuleManager.java

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package org.violetmoon.zeta.module;
22

33
import java.lang.reflect.Constructor;
4+
import java.lang.reflect.Field;
5+
import java.lang.reflect.Modifier;
46
import java.util.ArrayList;
57
import java.util.Collection;
68
import java.util.Comparator;
@@ -154,12 +156,41 @@ private ZetaModule constructAndSetup(TentativeModule t) {
154156
//category upkeep
155157
modulesInCategory.computeIfAbsent(module.category, __ -> new ArrayList<>()).add(module);
156158

159+
populateModuleInstanceField(module);
160+
157161
//post-construction callback
158162
module.postConstruct();
159163

160164
return module;
161165
}
162166

167+
// feel free to refactor
168+
private static void populateModuleInstanceField(ZetaModule module) {
169+
try {
170+
var clazz = module.getClass();
171+
Field[] fields = clazz.getDeclaredFields();
172+
Field targetField = null;
173+
174+
for (Field field : fields) {
175+
if (field.isAnnotationPresent(ModuleInstance.class)) {
176+
if (targetField != null) {
177+
throw new IllegalStateException("Can't have more than one @ModuleInstance field per module class");
178+
}
179+
if (!Modifier.isStatic(field.getModifiers())) {
180+
throw new IllegalStateException("@ModuleInstance annotated field must be static");
181+
}
182+
targetField = field;
183+
}
184+
}
185+
if(targetField != null) {
186+
targetField.setAccessible(true);
187+
targetField.set(null, module);
188+
}
189+
}catch (Exception e){
190+
throw new RuntimeException(e);
191+
}
192+
}
193+
163194
private <Z extends ZetaModule> Z construct(Class<Z> clazz) {
164195
try {
165196
Constructor<Z> cons = clazz.getConstructor();

0 commit comments

Comments
 (0)