Skip to content

Java Call Hierarchy Analyzer : A powerful open-source tool or utility for analyzing method call hierarchies in Java applications using bytecode analysis. This tool helps developers understand complex codebases by visualizing method call flows and dependencies.

License

Notifications You must be signed in to change notification settings

ravinderji/JCallTrace

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

JCallTrace (aka Java Call Hierarchy Analyzer)

License: MIT Java Version Maven

A powerful open-source tool for analyzing method call hierarchies in Java applications using bytecode analysis. This tool helps developers understand complex codebases by visualizing method call flows and dependencies.

🚀 Features

  • 📊 Method Call Analysis: Deep bytecode analysis using Apache BCEL
  • 🎯 Package Filtering: Focus analysis on specific packages
  • 📈 Excel Export: Generate detailed Excel reports with hierarchical structure
  • 🔧 Maven Integration: Automatic dependency resolution
  • 💻 Command Line Interface: Easy automation and CI/CD integration
  • 🛠️ Fluent API: Builder pattern for programmatic usage
  • 📋 Two Analysis Modes:
    • Linked Mode: Shows only methods directly connected to source class
    • All Mode: Comprehensive view of entire call hierarchy

📋 Table of Contents

⚡ Quick Start

Command Line

# Basic console analysis
java -jar call-hierarchy-analyzer.jar --class com.example.MyClass --packages com.example --pom /path/to/pom.xml

# Excel export with custom filename
java -jar call-hierarchy-analyzer.jar --class com.example.MyClass --packages com.example --pom /path/to/pom.xml --excel --output my-report.xlsx

# All methods analysis with Excel export
java -jar call-hierarchy-analyzer.jar --class com.example.MyClass --packages com.example --pom /path/to/pom.xml --excel --mode all --output detailed-analysis.xlsx

Programmatic API

// Simple usage
JCallHierarchy analyzer = new JCallHierarchy();
analyzer.analyzeAndPrintOnlyLinkedMethodCalls(
    "com.example.MyClass",
    new String[]{"com.example"},
    "/path/to/pom.xml",
    null
);

// Builder pattern (recommended)
JCallHierarchy.builder()
    .className("com.example.MyClass")
    .packages("com.example")
    .pomFile("/path/to/pom.xml")
    .generateExcel(true)
    .analyzeLinkedOnly();

📦 Installation

Prerequisites

  • Java 11 or higher
  • Maven 3.6+ (for Maven projects)

Build from Source

git clone https://github.com/your-repo/call-hierarchy-analyzer.git
cd call-hierarchy-analyzer
mvn clean install

Download JAR

Build from source to create JAR

📖 Usage

Command Line Interface

Basic Commands

# Console analysis only
java -jar analyzer.jar --class com.example.MyClass --pom /path/to/pom.xml

# Filter by packages
java -jar analyzer.jar --class com.example.MyClass --packages com.example,com.mycompany --pom /path/to/pom.xml

# Generate Excel report with custom filename
java -jar analyzer.jar --class com.example.MyClass --packages com.example --pom /path/to/pom.xml --excel --output my-analysis.xlsx

# Analyze all methods with Excel export
java -jar analyzer.jar --class com.example.MyClass --packages com.example --pom /path/to/pom.xml --excel --mode all --output complete-analysis.xlsx

Command Line Options

Option Description Required Default
--class Fully qualified class name -
--pom Path to POM file -
--packages Comma-separated package names All packages
--maven-home Maven home directory Auto-detected
--mode Analysis mode: linked or all linked
--excel Generate Excel output with custom filename false
--output Excel output filename (used with --excel) call_hierarchy.xlsx
--help Show help -

🔧 API Documentation

For detailed API documentation, see USAGE.md

Core Methods

// Analyze linked methods only
public void analyzeAndPrintOnlyLinkedMethodCalls(String className, String[] packages, String pomPath, String jarPath)

// Analyze all methods
public void analyzeAndPrintAllMethodCalls(String className, String[] packages, String pomPath, String jarPath)

// Get results as Map
public Map<String, Record> getOnlyLinkedClassesAndMethods(String className, String[] packages, String pomPath, String jarPath)

// Export to Excel
public void exportOnlyLinkedMethodCallsToExcel(String className, String[] packages, String pomPath, String jarPath, String fileName)

Builder Pattern API

JCallHierarchy.builder()
    .className("com.example.MyClass")
    .packages("com.example", "com.mycompany")
    .pomFile("/path/to/pom.xml")
    .generateExcel(true)
    .analyzeLinkedOnly();  // or .analyzeAll()

📊 Examples

Spring Boot Application

java -jar analyzer.jar \
  --class com.example.Application \
  --packages com.example \
  --pom /path/to/spring-boot-project/pom.xml \
  --excel --mode all --output spring-boot-analysis.xlsx

Microservice Analysis

JCallHierarchy.builder()
    .className("com.example.service.UserService")
    .packages("com.example.service", "com.example.repository")
    .pomFile("/path/to/pom.xml")
    .generateExcel(true)
    .analyzeLinkedOnly();

Analyzing Multiple Classes Using Wrapper Pattern

When you need to analyze multiple classes together, create a wrapper class that acts as a facade:

package com.example.analysis;

/**
 * Wrapper class to analyze multiple classes together.
 * Acts as a facade for all entry points that need to be analyzed.
 */
public class CallHierarchyAnalysisWrapper {
    
    public void analyzeAllComponents() {
        // Call all target classes and their entry methods
        analyzeUserService();
        analyzeOrderService();
        analyzePaymentService();
    }
    
    private void analyzeUserService() {
        com.example.service.UserService userService = new com.example.service.UserService();
        userService.createUser("sample");
        userService.getUserById(1L);
    }
    
    private void analyzeOrderService() {
        com.example.service.OrderService orderService = new com.example.service.OrderService();
        orderService.createOrder("order-123");
        orderService.processOrder("order-123");
    }
    
    private void analyzePaymentService() {
        com.example.service.PaymentService paymentService = new com.example.service.PaymentService();
        paymentService.processPayment(100.0);
    }
}

Analyze the wrapper class:

java -jar analyzer.jar \
  --class com.example.analysis.CallHierarchyAnalysisWrapper \
  --packages com.example \
  --pom /path/to/pom.xml \
  --excel --mode all \
  --output multi-class-analysis.xlsx

Benefits:

  • Analyze multiple classes in a single run
  • Get unified view of component interactions
  • Control which methods serve as entry points
  • Ideal for microservice or module analysis

CI/CD Integration

#!/bin/bash
# Generate call hierarchy report in pipeline with build-specific filename
java -jar call-hierarchy-analyzer.jar \
  --class ${MAIN_CLASS} \
  --packages ${PACKAGE_FILTER} \
  --pom ${WORKSPACE}/pom.xml \
  --excel \
  --output "call-hierarchy-${BUILD_NUMBER}.xlsx"

📈 Output Formats

Console Output (Default)

====================START============================

Caller:
|--L0 --> com.example.MyClass.mainMethod()

	|--L1 ---> com.example.service.UserService.getUser(String)
		|--L2 ---> com.example.repository.UserRepository.findById(String)
			|--L3 ---> com.example.database.DatabaseConnection.query(String)

====================END============================

Excel Output (With --excel --output filename.xlsx)

Excel files include:

  • Level: Hierarchy level (0, 1, 2, ...)
  • Class Name: Fully qualified class name
  • Method Name: Method name
  • Full Signature: Complete method signature
  • Next Immediate Linked Class: Called classes
  • Hierarchy: Visual representation
  • Custom Filename: User-specified via --output parameter
  • Location: Current working directory

🏗️ Building

# Build project
mvn clean compile

# Run tests
mvn test

# Create JAR
mvn package

# Install to local repository
mvn install

🧪 Testing

The project includes comprehensive JUnit 4 test suite with 21 test cases covering:

  • Positive Test Cases: Valid inputs and expected functionality
  • Negative Test Cases: Invalid inputs and error handling
  • Edge Cases: Null values, empty arrays, and boundary conditions
  • Performance Tests: Execution time validation (60-second timeout)
  • Integration Tests: Complete workflow testing
  • Excel Export Tests: File creation and content validation
  • Builder Pattern Tests: Fluent API functionality

Running Tests

# Run all tests
mvn test

# Run specific test class
mvn test -Dtest=JCallHierarchyTest

# Run tests with debug logging
mvn test -Dlog4j.configurationFile=src/main/resources/log4j2.xml

Test Coverage

  • ✅ All API methods (linked and all analysis modes)
  • ✅ Excel export functionality with custom filenames
  • ✅ Builder pattern API
  • ✅ Error handling and exception scenarios
  • ✅ Package filtering (null, empty, multiple packages)
  • ✅ Maven dependency resolution
  • ✅ Performance benchmarks
  • ✅ Complete integration workflows

🏛️ Architecture

src/main/java/codetumblr/poc/callhierarchy/
├── main/
│   └── JCallHierarchy.java          # Main API and CLI entry point
├── maven/
│   ├── MavenClassLoader.java        # Maven dependency class loading
│   └── MavenDependencyResolver.java # Maven dependency resolution
├── MethodCallAnalyzer.java          # Core bytecode analysis
└── Record.java                      # Call hierarchy data structure

🔍 How It Works

  1. Class Loading: Loads target class using Maven dependency resolution
  2. Bytecode Analysis: Uses Apache BCEL to analyze method calls in bytecode
  3. Call Graph Construction: Builds hierarchical call graph with level tracking
  4. Output Generation: Produces console output and/or Excel reports

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🙏 Acknowledgments

📞 Support

About

Java Call Hierarchy Analyzer : A powerful open-source tool or utility for analyzing method call hierarchies in Java applications using bytecode analysis. This tool helps developers understand complex codebases by visualizing method call flows and dependencies.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •  

Languages