cz.jalasoft.util.configuration.ConverterAnnotationIntrospection Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of JalasoftUtils Show documentation
Show all versions of JalasoftUtils Show documentation
A collection of utility classes that might be useful.
The newest version!
package cz.jalasoft.util.configuration;
import cz.jalasoft.util.configuration.annotation.Converter;
import cz.jalasoft.util.configuration.exception.ConverterInstantiationException;
import cz.jalasoft.util.converter.string.StringConverter;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.function.Consumer;
/**
* @author Honza Lastovicka ([email protected])
* @since 2016-07-30.
*/
public final class ConverterAnnotationIntrospection {
private final ConverterRegistry converterRegistry;
ConverterAnnotationIntrospection(ConverterRegistry converterRegistry) {
this.converterRegistry = converterRegistry;
}
void introspect(Class> type) {
forEachAnnotatedMethod(type, method -> {
introspectConverter(method);
});
}
private void forEachAnnotatedMethod(Class> type, Consumer consumer) {
Method[] methods = type.getDeclaredMethods();
Arrays.stream(methods).forEach(consumer);
}
private void introspectConverter(Method method) {
if (!method.isAnnotationPresent(Converter.class)) {
return;
}
Converter converterAnnotation = method.getAnnotation(Converter.class);
Class extends StringConverter>> converterType = converterAnnotation.value();
try {
StringConverter> converter = converterType.newInstance();
converterRegistry.addConverter(converter);
} catch (ReflectiveOperationException exc) {
throw new ConverterInstantiationException(converterType, exc);
}
}
}