mirror of
https://github.com/PolyhedralDev/Terra.git
synced 2026-04-19 23:00:19 +00:00
initialize manifest addons
This commit is contained in:
@@ -2,6 +2,7 @@ package com.dfsek.terra.api.inject;
|
||||
|
||||
import com.dfsek.terra.api.inject.annotations.Inject;
|
||||
import com.dfsek.terra.api.inject.exception.InjectionException;
|
||||
import com.dfsek.terra.api.inject.impl.InjectorImpl;
|
||||
|
||||
|
||||
/**
|
||||
@@ -37,4 +38,8 @@ public interface Injector<T> {
|
||||
* </ul>
|
||||
*/
|
||||
void inject(Object object) throws InjectionException;
|
||||
|
||||
static <T1> Injector<T1> get(T1 value) {
|
||||
return new InjectorImpl<>(value);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.dfsek.terra.api.inject.impl;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
import com.dfsek.terra.api.inject.Injector;
|
||||
import com.dfsek.terra.api.inject.annotations.Inject;
|
||||
import com.dfsek.terra.api.inject.exception.InjectionException;
|
||||
import com.dfsek.terra.api.util.reflection.ReflectionUtil;
|
||||
|
||||
|
||||
public class InjectorImpl<T> implements Injector<T> {
|
||||
private final T value;
|
||||
private final Set<Class<? extends T>> targets = new HashSet<>();
|
||||
|
||||
/**
|
||||
* Instantiate an Injector with a value to inject
|
||||
*
|
||||
* @param value Value to inject
|
||||
*/
|
||||
public InjectorImpl(T value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void addExplicitTarget(Class<? extends T> target) {
|
||||
targets.add(target);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void inject(Object object) throws InjectionException {
|
||||
for(Field field : ReflectionUtil.getFields(object.getClass())) {
|
||||
Inject inject = field.getAnnotation(Inject.class);
|
||||
if(inject == null) continue;
|
||||
if(value.getClass().equals(field.getType()) || targets.contains(field.getType())) {
|
||||
int mod = field.getModifiers();
|
||||
if(Modifier.isFinal(mod)) {
|
||||
throw new InjectionException("Attempted to inject final field: " + field);
|
||||
}
|
||||
if(Modifier.isStatic(mod)) {
|
||||
throw new InjectionException("Attempted to inject static field: " + field);
|
||||
}
|
||||
field.setAccessible(true);
|
||||
try {
|
||||
field.set(object, value);
|
||||
} catch(IllegalAccessException e) {
|
||||
throw new InjectionException("Failed to inject field: " + field, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user