com.syntaxphoenix.syntaxapi.data.DataAdapterRegistry Maven / Gradle / Ivy
The newest version!
package com.syntaxphoenix.syntaxapi.data;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import com.syntaxphoenix.syntaxapi.utils.java.Primitives;
public abstract class DataAdapterRegistry {
private final ConcurrentHashMap, DataAdapter, B, B>> adapters = new ConcurrentHashMap<>();
protected abstract DataAdapter buildAdapter(Class> clazz);
protected abstract DataAdapter createAdapter(Class primitiveType, Class resultType,
Function builder, Function extractor);
public B wrap(Class type, T value) {
DataAdapter, B, B> adapter = adapters.computeIfAbsent(Primitives.fromPrimitive(type), (clazz) -> buildAdapter(clazz));
return adapter == null ? null : adapter.build(value);
}
public T extract(Class type, B base) throws ClassCastException, IllegalArgumentException {
type = Primitives.fromPrimitive(type);
DataAdapter, B, B> adapter = this.adapters.computeIfAbsent(type, (clazz) -> buildAdapter(clazz));
if (adapter == null || !adapter.isInstance(base)) {
return null;
}
Object foundValue = adapter.extract(base);
return type.isInstance(foundValue) ? type.cast(foundValue) : null;
}
public boolean isInstanceOf(Class type, B base) {
DataAdapter, B, B> adapter = adapters.computeIfAbsent(Primitives.fromPrimitive(type), (clazz) -> buildAdapter(clazz));
return adapter == null ? null : adapter.isInstance(base);
}
public boolean hasAdapter(Class> type) {
return adapters.containsKey(Primitives.fromPrimitive(type));
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy