Java: avoiding ‘instanceOf’ operator

An interesting way to avoid ‘instanceOf’ operator (some developers hate it) is to use below mapper:

 

class Mapper {

        Map<Class, Function<Object, String>> mappers = Maps.newHashMap();

        Mapper() {
            mappers.put(Operator.class, o -> ((Operator) o).getSign());
            mappers.put(Boolean.class, Object::toString);
            mappers.put(Integer.class, Object::toString);
            mappers.put(Double.class, Object::toString);
            mappers.put(Long.class, Object::toString);
            mappers.put(String.class, s -> String.format("\"%s\"", s));
            mappers.put(List.class, l -> {
                StringBuilder stringBuilder = new StringBuilder("[");
                Iterator i = ((List) l).iterator();
                while (i.hasNext()) {
                    Object o = i.next();
                    stringBuilder.append(Mapper.this.map(o));
                    if (i.hasNext()) {
                        stringBuilder.append(",");
                    }
                }
                stringBuilder.append("]");
                return stringBuilder.toString();
            });
        }

        public String map(Object value) {
            for (Map.Entry<Class, Function<Object, String>> entry : mappers.entrySet()) {
                Class key = entry.getKey();
                if (key.isInterface() && asList(value.getClass().getInterfaces()).contains(key)
                    || Objects.equals(key, value.getClass())) {
                    return entry.getValue().apply(value);
                }
            }
            throw new UnsupportedOperationException();
        }
    }
Advertisements