mercredi 3 juin 2020

Java Map toString() where Map Value is Interface

I have many types of maps in my method. I've tried to make a mapToString() method to handle them, but some of my maps have interfaces as their key value.

    public <T> String interfaceToString(Class<T> clazz, Object instance) {
        log.info(clazz + "");

        StringBuilder toString = new StringBuilder("[ " + clazz.getSimpleName() + " - ");

        List<Method> methods = Arrays.asList(clazz.getDeclaredMethods());

        methods.forEach(method -> {
            try {
                toString.append(method.getName() + ": " + method.invoke(instance) + ", ");
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        });

        toString.replace(toString.length() - 2, toString.length() - 1, "");
        toString.append("]");

        return toString.toString();

    }

    public <T> String mapToString(Map<T, ?> map) {
        StringBuilder toString = new StringBuilder("[ ");

        for (T key : map.keySet()) {
            Object value = map.get(key);
            if (value.getClass().isInterface()) {
                toString.append(interfaceToString(value.getClass(), value));
            } else {
                toString.append("[" + key + ", " + value + "] ");
            }
        }

        toString.append(" ]");

        return toString.toString();
    }

It works for regular maps, but it just prints the object representation for map's whose key values are interfaces. I'm working with many interfaces, because I am using Spring JPA Projections to pull back partial parts of my database tables.

When I was debugging, when I logged value.getClass() in the mapToString, it's class was a Proxy. Which is why the isInterface() check failed when appending to the StringBuilder.

Is there a better way to do this?





Aucun commentaire:

Enregistrer un commentaire