Skip to content

Instantly share code, notes, and snippets.

@unnikked
Created December 23, 2016 22:01
Show Gist options
  • Save unnikked/cd04f9d99e4b2c8a2b26800d861e91fe to your computer and use it in GitHub Desktop.
Save unnikked/cd04f9d99e4b2c8a2b26800d861e91fe to your computer and use it in GitHub Desktop.
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.LinkedList;
import java.util.List;
public final class NaiveBuilder {
public static <T> T build(Class<T> aClass) throws IllegalAccessException, InvocationTargetException, InstantiationException {
Constructor<?> firstConstructor = aClass.getConstructors()[0];
if (hasDependencies(firstConstructor)) {
Object[] dependencies = resolve(firstConstructor);
return newInstance(firstConstructor, dependencies);
}
return newInstance(firstConstructor);
}
private static <T> T newInstance(Constructor<?> firstConstructor, Object... dependencies) throws InstantiationException, IllegalAccessException, InvocationTargetException {
return (T) firstConstructor.newInstance(dependencies);
}
private static Object[] resolve(Constructor<?> firstConstructor) throws IllegalAccessException, InstantiationException, InvocationTargetException {
List<Object> dependencies = new LinkedList<>();
for (Class<?> dependency : firstConstructor.getParameterTypes()) {
dependencies.add(build(dependency));
}
return dependencies.toArray();
}
private static boolean hasDependencies(Constructor<?> firstConstructor) {
return firstConstructor.getParameterTypes().length > 0;
}
public static void main(String[] args) throws IllegalAccessException, InstantiationException, InvocationTargetException {
A instance = NaiveBuilder.build(A.class);
System.out.println(instance);
}
}
class A {
private final B b;
private final C c;
public A(B b, C c) {
this.b = b;
this.c = c;
}
}
class B {
public B() {
}
}
class C {
private final D d;
public C(D d) {
this.d = d;
}
}
class D {
public D() {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment