Pages

Extract field name and values from Java Objects

 Suppose you have to write some generic utility which should extract the field name and values from Java DTO. 


Problem: There is a tracing library where you need to add a few critical fields and their values which will make the debugging very easier in any environment. Say, Jaeger.

Jaeger is a library which helps trace various class level calls in a microservices environment.

How would you convert the fields into Key value structure:

public static Map<String, String> extractFields(Object obj) {
    Map<String, String> map = new HashMap<>();

    if(obj == null) return map;

    Class<?> cls = obj.getClass();
    for(Field field: cls.getDeclaredFields()) {
        String name = field.getName();
        if("String".equals(field.getType().getSimpleName())) {
            field.setAccessible(true);
            try{
                String val = (String) field.get(obj);
                if(val != null) {
                    map.put(name, val);
                 }
            } catch(IllegalAccessException e) {
                Logger.error("Error extracting {} field", field);
            }
        }
    }
    return map;
}