package org.jdbi.v3.core.mapper.reflect;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import org.jdbi.v3.core.internal.exceptions.Unchecked;
import static java.lang.String.format;
import static java.util.Objects.requireNonNull;
class StaticMethodInstanceFactory<T> extends InstanceFactory<T> {
private final Class<T> type;
private final Method method;
StaticMethodInstanceFactory(Class<T> type, Method method) {
super(method);
this.type = requireNonNull(type, "type is null");
requireNonNull(method, "method is null");
if (!isStaticFactoryMethodFor(method, type)) {
throw new IllegalArgumentException(format("Given method \"%s\" is not a valid factory method for %s", method, type));
}
this.method = method;
}
private static boolean isStaticFactoryMethodFor(Method method, Class<?> type) {
return Modifier.isStatic(method.getModifiers())
&& type.isAssignableFrom(method.getReturnType());
}
@Override
T newInstance(Object... params) {
return type.cast(Unchecked.<Object, Object[], Object>biFunction(method::invoke).apply(null, params));
}
@Override
public String toString() {
return method.toString();
}
}