Skip to content

Commit

Permalink
separate if condition into private method
Browse files Browse the repository at this point in the history
  • Loading branch information
IvanFadieiev committed Aug 8, 2023
1 parent 60eb872 commit 07cb1f8
Showing 1 changed file with 24 additions and 20 deletions.
44 changes: 24 additions & 20 deletions src/main/java/mate.academy/lib/Injector.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,29 +26,33 @@ public static Injector getInjector() {
public Object getInstance(Class<?> interfaceClazz) {
Object clazzImplementationInstance = null;
Class<?> clazz = findImplementation(interfaceClazz);
if (clazz.isAnnotationPresent(Component.class)) {
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
if (field.isAnnotationPresent(Inject.class)) {
Object fieldInstance = getInstance(field.getType());
clazzImplementationInstance = createNewInstance(clazz);
try {
field.setAccessible(true);
field.set(clazzImplementationInstance, fieldInstance);
} catch (IllegalAccessException e) {
throw new RuntimeException("Can't initialize field value. "
+ "Class; " + clazz.getName() + ". Field " + field.getName());
}
}
}
if (clazzImplementationInstance == null) {
checkIfAnnotationPresent(interfaceClazz, clazz);
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
if (field.isAnnotationPresent(Inject.class)) {
Object fieldInstance = getInstance(field.getType());
clazzImplementationInstance = createNewInstance(clazz);
try {
field.setAccessible(true);
field.set(clazzImplementationInstance, fieldInstance);
} catch (IllegalAccessException e) {
throw new RuntimeException("Can't initialize field value. "
+ "Class; " + clazz.getName() + ". Field " + field.getName());
}
}
return clazzImplementationInstance;
}
throw new RuntimeException("Provided class "
+ interfaceClazz.getName()
+ " is not marked with Component annotation");
if (clazzImplementationInstance == null) {
clazzImplementationInstance = createNewInstance(clazz);
}
return clazzImplementationInstance;
}

private void checkIfAnnotationPresent(Class<?> interfaceClazz, Class<?> clazz) {
if (!clazz.isAnnotationPresent(Component.class)) {
throw new RuntimeException("Provided class "
+ interfaceClazz.getName()
+ " is not marked with Component annotation");
}
}

private Object createNewInstance(Class<?> clazz) {
Expand Down

0 comments on commit 07cb1f8

Please sign in to comment.