|
1 | 1 | package org.violetmoon.zeta.module;
|
2 | 2 |
|
3 | 3 | import java.lang.reflect.Constructor;
|
| 4 | +import java.lang.reflect.Field; |
| 5 | +import java.lang.reflect.Modifier; |
4 | 6 | import java.util.ArrayList;
|
5 | 7 | import java.util.Collection;
|
6 | 8 | import java.util.Comparator;
|
@@ -154,12 +156,41 @@ private ZetaModule constructAndSetup(TentativeModule t) {
|
154 | 156 | //category upkeep
|
155 | 157 | modulesInCategory.computeIfAbsent(module.category, __ -> new ArrayList<>()).add(module);
|
156 | 158 |
|
| 159 | + populateModuleInstanceField(module); |
| 160 | + |
157 | 161 | //post-construction callback
|
158 | 162 | module.postConstruct();
|
159 | 163 |
|
160 | 164 | return module;
|
161 | 165 | }
|
162 | 166 |
|
| 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 | + |
163 | 194 | private <Z extends ZetaModule> Z construct(Class<Z> clazz) {
|
164 | 195 | try {
|
165 | 196 | Constructor<Z> cons = clazz.getConstructor();
|
|
0 commit comments