Skip to content

Commit

Permalink
Implemented Injector uses @component and @Inject. Add customize excep…
Browse files Browse the repository at this point in the history
…tion ComponentException.
  • Loading branch information
OlegStashkiv committed Aug 7, 2023
1 parent 00d5c92 commit b3be758
Showing 1 changed file with 7 additions and 4 deletions.
11 changes: 7 additions & 4 deletions src/main/java/mate.academy/lib/Injector.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,13 @@ public static Injector getInjector() {
public Object getInstance(Class<?> interfaceClazz) {
Object clazzImplementationInstance = null;
Class<?> clazz = findImplementation(interfaceClazz);

if (!clazz.isAnnotationPresent(Component.class)) {
throw new ComponentException("Injection failed, "
+ "missing @Component annotation on the class: "
+ clazz.getName());
}

Field[] declaredFields = clazz.getDeclaredFields();
for (Field field : declaredFields) {
if (field.isAnnotationPresent(Inject.class)) {
Expand All @@ -51,10 +58,6 @@ private Object createNewInstance(Class<?> clazz) {
if (instances.containsKey(clazz)) {
return instances.get(clazz);
}
if (!clazz.isAnnotationPresent(Component.class)) {
throw new ComponentException("A class must be annotated with a component annotation:"
+ clazz.getName());
}
try {
Constructor<?> constructor = clazz.getConstructor();
Object instance = constructor.newInstance();
Expand Down

0 comments on commit b3be758

Please sign in to comment.