DEV Community

Query Filter
Query Filter

Posted on

bridge-14

/**
 * Walks the current thread's stack trace to find the class containing 
 * the main method entry point and returns its Class type.
 */
public static Class<?> autoDiscoverMainClass() {
    try {
        String mainClassName = null;
        for (StackTraceElement element : Thread.currentThread().getStackTrace()) {
            if ("main".equals(element.getMethodName())) {
                mainClassName = element.getClassName();
                break;
            }
        }

        if (mainClassName != null) {
            return Class.forName(mainClassName);
        }
    } catch (Exception e) {
        System.err.println("[PROFILER-AGENT] Failed to auto-discover main class token: " + e.getMessage());
    }

    // Fallback if the thread trace fails or is empty
    return null;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)