Utils.java

package org.docascode.api.core.office;

import org.docx4j.XmlUtils;
import org.docx4j.wml.ContentAccessor;

import java.util.ArrayList;
import java.util.List;

public class Utils {
    private Utils(){
        //Prevent public constructor
    }

    public static <T> List<T> getTargetElements(Object source, Class<T> targetClass) {
        List<T> result = new ArrayList<>();
        Object target = XmlUtils.unwrap(source);
        if (targetClass.isAssignableFrom(target.getClass())) {
            result.add((T) target);
        } else if (target instanceof ContentAccessor) {
            List<?> children = ((ContentAccessor) target).getContent();
            for (Object child : children) {
                result.addAll(getTargetElements(child, targetClass));
            }
        }
        return result;
    }
}