Skip to content

Commit

Permalink
Added @ModuleInstance annotation. Annotate a static field inside your…
Browse files Browse the repository at this point in the history
… module class to have it populated with its instance, allowing for easy singleton patterns. This is opt in
  • Loading branch information
MehVahdJukaar committed Jul 28, 2024
1 parent ccac3d9 commit 832410e
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/main/java/org/violetmoon/zeta/module/ModuleInstance.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package org.violetmoon.zeta.module;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

// populates a public static field in your module class with the module instance. Needs to be inside a @ZetaLoadModule class
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ModuleInstance {

}
31 changes: 31 additions & 0 deletions src/main/java/org/violetmoon/zeta/module/ZetaModuleManager.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package org.violetmoon.zeta.module;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
Expand Down Expand Up @@ -154,12 +156,41 @@ private ZetaModule constructAndSetup(TentativeModule t) {
//category upkeep
modulesInCategory.computeIfAbsent(module.category, __ -> new ArrayList<>()).add(module);

populateModuleInstanceField(module);

//post-construction callback
module.postConstruct();

return module;
}

// feel free to refactor
private static void populateModuleInstanceField(ZetaModule module) {
try {
var clazz = module.getClass();
Field[] fields = clazz.getDeclaredFields();
Field targetField = null;

for (Field field : fields) {
if (field.isAnnotationPresent(ModuleInstance.class)) {
if (targetField != null) {
throw new IllegalStateException("Can't have more than one @ModuleInstance field per module class");
}
if (!Modifier.isStatic(field.getModifiers())) {
throw new IllegalStateException("@ModuleInstance annotated field must be static");
}
targetField = field;
}
}
if(targetField != null) {
targetField.setAccessible(true);
targetField.set(null, module);
}
}catch (Exception e){
throw new RuntimeException(e);
}
}

private <Z extends ZetaModule> Z construct(Class<Z> clazz) {
try {
Constructor<Z> cons = clazz.getConstructor();
Expand Down

0 comments on commit 832410e

Please sign in to comment.