Prints a trace message to stdout that gives info about the method that calls this method. - Java java.lang

Java examples for java.lang:Throwable

Description

Prints a trace message to stdout that gives info about the method that calls this method.

Demo Code

/*******************************************************************************
 * Copyright (c) 2006, 2009 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:/*from   ww w  .  ja v  a  2 s . c o  m*/
 *     Mike Kucera (IBM Corporation) - initial API and implementation
 *******************************************************************************/
//package com.java2s;

public class Main {
    /**
     * Prints a trace message to stdout that gives info
     * about the method that calls this method.
     */
    public static void printMethodTrace() {
        StackTraceElement[] trace = Thread.currentThread().getStackTrace();
        printMethodTrace(trace, null);
    }

    /**
     * Prints a trace message to stdout that gives info
     * about the method that calls this method.
     * 
     * The output is in a format that will show up as a hyperlink in the eclipse console.
     */
    public static void printMethodTrace(String extraMessage) {
        StackTraceElement[] trace = Thread.currentThread().getStackTrace();
        printMethodTrace(trace, extraMessage);
    }

    private static void printMethodTrace(StackTraceElement[] trace,
            String extraMessage) {
        StackTraceElement caller = trace[3];

        String className = caller.getClassName();
        className = className.substring(className.lastIndexOf(".") + 1);

        String message = String.format("%s.%s(%s:%d)", className,
                caller.getMethodName(), caller.getFileName(),
                caller.getLineNumber());

        if (extraMessage != null)
            message += ": " + extraMessage;

        System.out.println(message);
    }
}

Related Tutorials