Last active
August 14, 2018 07:11
-
-
Save joecheatham/74d1c14eee6bcedff35fb476a0c847d3 to your computer and use it in GitHub Desktop.
simple and inefficient java "dependency injection" utility
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.lang.reflect.Constructor; | |
import java.util.HashMap; | |
import java.util.Map; | |
public class SimpleDI { | |
private static final SimpleDI INSTANCE = new SimpleDI(); | |
private final Map <Class<?>, Object> classMap = new HashMap <>(); | |
public static void init(Object...objects) { | |
for (Object obj: objects) { | |
insertAll(obj.getClass(), obj); | |
} | |
} | |
public static <T> T inject(Class <T> className) { | |
try { | |
if (!INSTANCE.classMap.containsKey(className)) { | |
Constructor<?> constructor = className.getConstructors()[0]; | |
Class<?> [] args = constructor.getParameterTypes(); | |
Object[] instances = new Object[args.length]; | |
for (int i = 0; i < args.length; i++) { | |
if (!INSTANCE.classMap.containsKey(args[i])) { | |
inject(args[i]); | |
} | |
instances[i] = INSTANCE.classMap.get(args[i]); | |
} | |
T instance = (T) constructor.newInstance(instances); | |
insertAll(className, instance); | |
} | |
return (T) INSTANCE.classMap.get(className); | |
} catch (Exception e) { | |
return null; | |
} | |
} | |
private static void insertAll(Class <?> clazz, Object obj) { | |
Class <?> superClass = clazz.getSuperclass(); | |
if (superClass != null) { | |
insertAll(superClass, obj); | |
} | |
for (Class <?> interf : clazz.getInterfaces()) { | |
INSTANCE.classMap.put(interf, obj); | |
} | |
INSTANCE.classMap.put(clazz, obj); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
usage example with POJOs A, B
calling this main method would print "hello, B" twice.
you can also init the util with any classes you wish, a quick Android example:
you now have access to any of the implemented interfaces or superclasses of
SomeActivity
, includingContext
. this can be seen in the following extended example:even though the util was never initialized with a
Context
, it found the superclass on theSomeActivity
instance to inject as a dependency toToaster
. so whenmakeToast()
is called, the toast with text "some toast" is displayed.this util only supports singleton injection, no additional scopes are planned