Skip to main content
Glama

get_class_info

Retrieve Java class information from running JVM processes using jmap and javap commands to analyze class structures, memory usage, and implementation details for debugging and monitoring.

Instructions

获取类信息 - 使用jmap -histo和javap命令获取完整的类信息

        Args:
            pid (str): 进程ID,使用字符串形式(如:"12345")
            class_pattern (str): 类名表达式匹配
            show_detail (bool): 是否显示详细信息,默认false
            show_field (bool): 是否显示成员变量信息(需要show_detail=True),默认false
            use_regex (bool): 是否使用正则表达式匹配,默认false
            depth (str): 属性遍历深度(暂未使用)
            classloader_hash (Optional[str]): 指定class的ClassLoader的hashcode(暂未使用)
            classloader_class (Optional[str]): 指定执行表达式的ClassLoader的class name(暂未使用)
            max_matches (str): 匹配类的最大数量,使用字符串形式(如:"50")

        Returns:
            Dict: 包含类信息的字典
        

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pidNo
class_patternNo
show_detailNo
show_fieldNo
use_regexNo
depthNo
classloader_hashNo
classloader_classNo
max_matchesNo

Implementation Reference

  • The MCP tool handler for get_class_info. Validates inputs, imports and instantiates ClassInfoCoordinator, calls get_class_info_parallel to perform the core logic.
    @self.mcp.tool()
    def get_class_info(pid: str = "", 
                      class_pattern: str = "",
                      show_detail: bool = False,
                      show_field: bool = False,
                      use_regex: bool = False,
                      depth: str = "",
                      classloader_hash: Optional[str] = None,
                      classloader_class: Optional[str] = None,
                      max_matches: str = "") -> Dict:
        """获取类信息 - 使用jmap -histo和javap命令获取完整的类信息
        
        Args:
            pid (str): 进程ID,使用字符串形式(如:"12345")
            class_pattern (str): 类名表达式匹配
            show_detail (bool): 是否显示详细信息,默认false
            show_field (bool): 是否显示成员变量信息(需要show_detail=True),默认false
            use_regex (bool): 是否使用正则表达式匹配,默认false
            depth (str): 属性遍历深度(暂未使用)
            classloader_hash (Optional[str]): 指定class的ClassLoader的hashcode(暂未使用)
            classloader_class (Optional[str]): 指定执行表达式的ClassLoader的class name(暂未使用)
            max_matches (str): 匹配类的最大数量,使用字符串形式(如:"50")
    
        Returns:
            Dict: 包含类信息的字典
        """
        # 验证 pid 参数
        validated_pid = self._validate_and_convert_id(pid if pid else None, "Process ID")
        if validated_pid is None:
            return {"success": False, "error": "有效的进程ID是必须的"}
        
        # 验证 max_matches 参数
        validated_max_matches = None
        if max_matches:
            validated_max_matches = self._validate_and_convert_id(max_matches, "Max matches")
            if validated_max_matches is None or validated_max_matches <= 0:
                return {"success": False, "error": "max_matches必须是正整数"}
        
        try:
            # 创建 ClassInfoCoordinator 实例
            from .native.base import NativeCommandExecutor
            from .native.tools import ClassInfoCoordinator
            
            executor = NativeCommandExecutor()
            coordinator = ClassInfoCoordinator(executor)
            
            # 调用协调器获取类信息
            result = coordinator.get_class_info_parallel(
                pid=str(validated_pid),
                class_pattern=class_pattern,
                show_detail=show_detail,
                show_field=show_field,
                use_regex=use_regex,
                max_matches=validated_max_matches
            )
            
            return result
            
        except Exception as e:
            return {
                "success": False,
                "error": f"获取类信息时发生错误: {str(e)}",
                "classes": [],
                "total_matches": 0,
                "limited_by_max": False
            }
  • Core helper method implementing the class info retrieval: jmap histogram for stats, filtering, optional javap for structure.
    def get_class_info(self, pid: str, class_pattern: str = "", 
                      show_detail: bool = False, show_field: bool = False,
                      use_regex: bool = False, max_matches: Optional[int] = None,
                      **kwargs) -> Dict[str, Any]:
        """获取类信息
    
        Args:
            pid: 进程ID
            class_pattern: 类名模式匹配
            show_detail: 是否显示详细信息
            show_field: 是否显示字段信息
            use_regex: 是否使用正则表达式匹配
            max_matches: 最大匹配数量
    
        Returns:
            Dict[str, Any]: 包含类信息的字典
        """
        try:
            # 第一步:使用 jmap -histo 获取运行时统计信息
            jmap_result = self.jmap_histo_cmd.execute(
                pid=pid, 
                operation=JmapOperation.HISTO,
                live_only=kwargs.get('live_only', False)
            )
            
            if not jmap_result.get('success', False):
                return {
                    "success": False,
                    "error": f"Failed to get histogram data: {jmap_result.get('error', 'Unknown error')}",
                    "classes": [],
                    "total_matches": 0,
                    "limited_by_max": False
                }
    
            # 第二步:提取和过滤类信息
            histogram = jmap_result.get('histogram', [])
            filtered_classes = self._filter_classes(histogram, class_pattern, use_regex)
            
            # 第三步:应用最大匹配限制
            limited_by_max = False
            if max_matches and len(filtered_classes) > max_matches:
                filtered_classes = filtered_classes[:max_matches]
                limited_by_max = True
    
            # 第四步:构建基础结果
            classes_info = []
            for class_data in filtered_classes:
                class_info = {
                    "class_name": class_data["class_name"],
                    "runtime_info": {
                        "instances": class_data["instances"],
                        "bytes": class_data["bytes"],
                        "rank": len(classes_info) + 1  # 排名基于内存使用顺序
                    }
                }
                
                # 第五步:如果需要详细信息,获取结构信息
                if show_detail:
                    structure_info = self._get_structure_info(
                        class_data["class_name"], 
                        show_field,
                        **kwargs
                    )
                    if structure_info:
                        class_info["structure_info"] = structure_info
    
                classes_info.append(class_info)
    
            return {
                "success": True,
                "classes": classes_info,
                "total_matches": len(classes_info),
                "limited_by_max": limited_by_max,
                "error": None
            }
    
        except Exception as e:
            return {
                "success": False,
                "error": f"Coordinator error: {str(e)}",
                "classes": [],
                "total_matches": 0,
                "limited_by_max": False
            }
  • Parallel helper method for detailed class info: gets base stats then parallelizes javap calls for structure info across classes.
    def get_class_info_parallel(self, pid: str, class_pattern: str = "", 
                               show_detail: bool = False, show_field: bool = False,
                               use_regex: bool = False, max_matches: Optional[int] = None,
                               max_workers: int = 5, **kwargs) -> Dict[str, Any]:
        """并行获取类信息(优化版本)
    
        Args:
            pid: 进程ID
            class_pattern: 类名模式匹配
            show_detail: 是否显示详细信息
            show_field: 是否显示字段信息
            use_regex: 是否使用正则表达式匹配
            max_matches: 最大匹配数量
            max_workers: 最大工作线程数
    
        Returns:
            Dict[str, Any]: 包含类信息的字典
        """
        if not show_detail:
            # 如果不需要详细信息,使用普通版本
            return self.get_class_info(
                pid, class_pattern, show_detail, show_field, 
                use_regex, max_matches, **kwargs
            )
    
        try:
            # 第一步:获取基础信息
            base_result = self.get_class_info(
                pid, class_pattern, False, False, 
                use_regex, max_matches, **kwargs
            )
            
            if not base_result.get('success', False):
                return base_result
    
            classes_info = base_result["classes"]
            
            # 第二步:并行获取结构信息
            if classes_info:
                self._parallel_get_structure_info(
                    classes_info, show_field, max_workers, **kwargs
                )
    
            return {
                "success": True,
                "classes": classes_info,
                "total_matches": base_result["total_matches"],
                "limited_by_max": base_result["limited_by_max"],
                "error": None
            }
    
        except Exception as e:
            return {
                "success": False,
                "error": f"Parallel coordinator error: {str(e)}",
                "classes": [],
                "total_matches": 0,
                "limited_by_max": False
            }
  • Helper for filtering histogram classes by pattern, supporting regex or wildcard matching.
    def _filter_classes(self, histogram: List[Dict[str, Any]], 
                       pattern: str, use_regex: bool) -> List[Dict[str, Any]]:
        """过滤类列表
    
        Args:
            histogram: jmap 直方图数据
            pattern: 过滤模式
            use_regex: 是否使用正则表达式
    
        Returns:
            List[Dict[str, Any]]: 过滤后的类列表
        """
        if not pattern:
            return histogram
    
        filtered = []
        
        try:
            for class_data in histogram:
                class_name = class_data.get("class_name", "")
                
                if use_regex:
                    # 使用正则表达式匹配
                    if re.search(pattern, class_name, re.IGNORECASE):
                        filtered.append(class_data)
                else:
                    # 使用通配符匹配
                    if fnmatch.fnmatch(class_name.lower(), pattern.lower()):
                        filtered.append(class_data)
                        
        except re.error as e:
            # 正则表达式错误,返回原始列表
            return histogram
            
        return filtered

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/xzq-xu/jvm-mcp-server'

If you have feedback or need assistance with the MCP directory API, please join our Discord server