com.softicar.platform.common.container.map.instance.ClassInstanceMap Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of platform-common Show documentation
Show all versions of platform-common Show documentation
The SoftiCAR Platform is a lightweight, Java-based library to create interactive business web applications.
package com.softicar.platform.common.container.map.instance;
import com.softicar.platform.common.core.exceptions.SofticarDeveloperException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Supplier;
/**
* This class maps classes to an single instance of that class.
*
* @author Oliver Richers
*/
public class ClassInstanceMap {
private final Map, T> map = new HashMap<>();
public void putInstance(I instance) {
Objects.requireNonNull(instance);
map.put(instance.getClass(), instance);
}
public void putInstanceIfAbsent(I instance) {
Objects.requireNonNull(instance);
map.putIfAbsent(instance.getClass(), instance);
}
public Optional getOptional(Class instanceClass) {
Objects.requireNonNull(instanceClass);
Object instance = map.get(instanceClass);
return Optional.ofNullable(instanceClass.cast(instance));
}
public I getOrPutInstance(Class instanceClass, Supplier instanceFactory) {
Object instance = map.get(instanceClass);
if (instance != null) {
return instanceClass.cast(instance);
} else {
I newInstance = instanceFactory.get();
assertCorrectClass(instanceClass, newInstance);
putInstance(newInstance);
return newInstance;
}
}
public Collection getAll() {
return map.values();
}
private static void assertCorrectClass(Class instanceClass, I newInstance) {
if (newInstance.getClass() != instanceClass) {
throw new SofticarDeveloperException(//
"Constructed data is of type '%s' but should be '%s'.",
newInstance.getClass().getCanonicalName(),
instanceClass.getCanonicalName());
}
}
}