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

com.javacook.enumcheck.EnumCheck Maven / Gradle / Ivy

Go to download

Utility to guarantee that all getters and setters of an object have been invoked, mainly in case of bean mappings

The newest version!
package com.javacook.enumcheck;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Function;


public class EnumCheck {

    public static , D extends Enum>
    Set sourceValuesNotMapped(Function mapper, Class enumSource) {

        Set valueSetSource = new HashSet<>(Arrays.asList(values(enumSource)));
        Set result = new HashSet<>();
        for (S s : valueSetSource) {
            try {
                mapper.apply(s);
            }
            catch (Exception e) {
                result.add(s);
            }
        }
        return result;
    }


    public static , D extends Enum>
    Set destValuesNotMapped(Function mapper, Class enumSource, Class enumDest) {

        Set valueSetSource = new HashSet<>(Arrays.asList(values(enumSource)));
        Set valueSetDest = new HashSet<>(Arrays.asList(values(enumDest)));
        Set mappedValues = new HashSet<>();
        for (S s : valueSetSource) {
            try {
                mappedValues.add((D) mapper.apply(s));
            }
            catch (Exception e) {}
        }
        valueSetDest.removeAll(mappedValues);
        return valueSetDest;
    }


    private static > S[] values(Class enumSource) {
        try {
            final Method methodSource = enumSource.getMethod("values");
            return (S[]) methodSource.invoke(enumSource);
        }
        catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}