support creating of types with default constructors (for plugins)

This commit is contained in:
Anton Keks 2020-05-17 20:40:33 +03:00
parent e3db855b50
commit 5d8db9c687
2 changed files with 6 additions and 5 deletions

View File

@ -42,11 +42,12 @@ public class Injector {
}
private <T> T createInstance(Class<T> type) {
Constructor<T> constructor = (Constructor<T>) stream(type.getConstructors())
.filter(c -> c.isAnnotationPresent(Inject.class)).findAny()
.orElseThrow(() -> new InjectException(type.getName() + " has no constructors annotated with @Inject"));
Constructor<T>[] constructors = (Constructor<T>[]) type.getConstructors();
Constructor<T> constructor = stream(constructors).filter(c -> c.isAnnotationPresent(Inject.class)).findAny().orElse(null);
if (constructor == null && constructors.length == 1) constructor = constructors[0];
try {
return constructor.newInstance(resolveDeps(constructor));
if (constructor != null) return constructor.newInstance(resolveDeps(constructor));
else throw new InjectException(type.getName() + " has no default constructor or a constructor annotated with @Inject");
}
catch (Exception e) {
throw new InjectException("Cannot create " + type.getName() + ", deps: " + Arrays.toString(constructor.getGenericParameterTypes()), e);

View File

@ -33,7 +33,7 @@ public class InjectorTest {
}
static class Dummy {
@Inject public Dummy() {}
public Dummy() {}
}
static class WithDeps {