-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathInjector.java
More file actions
57 lines (44 loc) · 1.95 KB
/
Copy pathInjector.java
File metadata and controls
57 lines (44 loc) · 1.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package mate.academy.lib;
import java.lang.reflect.Field;
import java.util.Map;
import mate.academy.service.FileReaderService;
import mate.academy.service.ProductParser;
import mate.academy.service.ProductService;
import mate.academy.service.impl.FileReaderServiceImpl;
import mate.academy.service.impl.ProductParserImpl;
import mate.academy.service.impl.ProductServiceImpl;
public class Injector {
private static final Injector injector = new Injector();
private final Map<Class<?>, Class<?>> interfacesImpl = Map.of(
ProductService.class, ProductServiceImpl.class,
ProductParser.class, ProductParserImpl.class,
FileReaderService.class, FileReaderServiceImpl.class);
public static Injector getInjector() {
return injector;
}
public Object getInstance(Class<?> interfaceClazz) {
Class<?> implementationClass = interfacesImpl.get(interfaceClazz);
if (implementationClass == null) {
throw new RuntimeException(
"No implementation class found for " + interfaceClazz.getName());
}
if (!implementationClass.isAnnotationPresent(Component.class)) {
throw new RuntimeException(
"No @Component annotation found for " + interfaceClazz.getName());
}
try {
Object instance = implementationClass.getDeclaredConstructor().newInstance();
Field[] fields = implementationClass.getDeclaredFields();
for (Field field : fields) {
if (field.isAnnotationPresent(Inject.class)) {
Object dependency = getInstance(field.getType());
field.setAccessible(true);
field.set(instance, dependency);
}
}
return instance;
} catch (ReflectiveOperationException e) {
throw new RuntimeException("Unable to instantiate " + implementationClass.getName(), e);
}
}
}