All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cz.jalasoft.util.configuration.ConverterAnnotationIntrospection Maven / Gradle / Ivy

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> converterType = converterAnnotation.value();

        try {
            StringConverter converter = converterType.newInstance();
            converterRegistry.addConverter(converter);
        } catch (ReflectiveOperationException exc) {
            throw new ConverterInstantiationException(converterType, exc);
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy