private static Map<ObjectName, Integer> findNumExpectedAttributes(MBeanServerConnection conn,
                                                                      Optional<String[]> attributesInclude,
                                                                      boolean hasPatternQueries,
                                                                      List<ObjectName> queries,
                                                                      Set<ObjectName> found) throws Exception {
        Map<ObjectName, Integer> result = new HashMap<>();
        if (!attributesInclude.isPresent()) {
            found.forEach(objectName -> {
                try {
                    MBeanInfo mBeanInfo = conn.getMBeanInfo(objectName);
                    result.put(objectName, conn.getAttributes(objectName, attributesNames(mBeanInfo)).size());
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            });
        } else {
            if (hasPatternQueries) {
                found.forEach(objectName -> {
                    try {
                        MBeanInfo mBeanInfo = conn.getMBeanInfo(objectName);
                        AttributeList attributes = conn.getAttributes(objectName, attributesNames(mBeanInfo));
                        List<ObjectName> expectedAttributes = new ArrayList<>();
                        attributes.asList().forEach(attribute -> {
                            if (Arrays.asList(attributesInclude.get()).contains(attribute.getName())) {
                                expectedAttributes.add(objectName);
                            }
                        });
                        if (expectedAttributes.size() > 0) {
                            result.put(objectName, expectedAttributes.size());
                        }
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                });
            } else {
                found.forEach(objectName -> result.put(objectName, attributesInclude.get().length));
            }
        }

        if (result.isEmpty()) {
            throw new TerseException(String.format("No matched attributes for the queried objects %s.", queries));
        }
        return result;
    }
A program for reading JMX metrics from a given endpoint.
<p>
This tool only works reliably if the JmxServer is fully initialized prior to invoking the tool.
See KAFKA-4620 for details.
tools/src/main/java/org/apache/kafka/tools/JmxTool.java