Cutin/lib/src/main/java/net/tomatentum/cutin/ReflectedMethodFactoryImpl.java

62 lines
2.0 KiB
Java

package net.tomatentum.cutin;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.tomatentum.cutin.method.ReflectedMethod;
import net.tomatentum.cutin.util.ReflectionUtil;
public class ReflectedMethodFactoryImpl<I extends Object, C extends Object> implements ReflectedMethodFactory<I, C> {
private Logger logger = LoggerFactory.getLogger(getClass());
private List<Factory<I, C>> factories;
public ReflectedMethodFactoryImpl() {
this(new ArrayList<>());
}
public ReflectedMethodFactoryImpl(List<Factory<I, C>> factories) {
this.factories = factories;
}
@Override
public Optional<ReflectedMethod<I, C>> produce(Method method, Object containingClass) {
Optional<ReflectedMethod<I, C>> rmethod = this.factories.stream()
.map(f -> factoryProduce(f, method, containingClass))
.filter(Optional::isPresent)
.map(Optional::get)
.findFirst();
if (rmethod.isEmpty())
logger.warn("Could not produce a ReflectedMethod for Method {} in {}", ReflectionUtil.getFullMethodName(method), this);
else
logger.debug("Produced {} for Method {} in {}", rmethod.get(), ReflectionUtil.getFullMethodName(method), this);
return rmethod;
}
@Override
public ReflectedMethodFactory<I, C> addFactory(Factory<I, C> factory) {
this.factories.add(factory);
logger.trace("Added Factory {} to {}", factory, this);
return this;
}
private Optional<ReflectedMethod<I, C>> factoryProduce(Factory<I, C> factory, Method method, Object containingClass) {
Set<MethodParser> parser = new HashSet<>();
factory.addParser(parser);
ParserResults results = ParserResults.create(parser, method, containingClass);
return factory.produce(method, containingClass, results);
}
}