`

StackTraceElement 源码

阅读更多
/*
 * %W% %E%
 *
 * Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

package java.lang;

/**
 * An element in a stack trace, as returned by {@link
 * Throwable#getStackTrace()}.  Each element represents a single stack frame.
 * All stack frames except for the one at the top of the stack represent
 * a method invocation.  The frame at the top of the stack represents the 
 * execution point at which the stack trace was generated.  Typically,
 * this is the point at which the throwable corresponding to the stack trace
 * was created.
 * 堆栈跟踪中的元素,它由 Throwable.getStackTrace() 返回。
 * 每个元素表示单独的一个堆栈帧。所有的堆栈帧
 *(堆栈顶部的那个堆栈帧除外) 都表示一个方法调用。
 * 堆栈顶部的帧表示生成堆栈跟踪的执行点。通常,
 * 这是创建对应于堆栈跟踪的  throwable 的点。
 *
 * @since  1.4
 * @author Josh Bloch
 */
public final class StackTraceElement implements java.io.Serializable {
    // Normally initialized by VM (public constructor added in 1.5)
    private String declaringClass;
    private String methodName;
    private String fileName;
    private int    lineNumber;

    /**
     * Creates a stack trace element representing the specified execution
     * point.
     * 创建表示指定执行点的堆栈跟踪元素
     *
     * @param declaringClass the fully qualified name of the class containing
     *        the execution point represented by the stack trace element
     * @param methodName the name of the method containing the execution point
     *        represented by the stack trace element
     * @param fileName the name of the file containing the execution point
     *         represented by the stack trace element, or <tt>null</tt> if
     *         this information is unavailable
     * @param lineNumber the line number of the source line containing the
     *         execution point represented by this stack trace element, or
     *         a negative number if this information is unavailable. A value
     *         of -2 indicates that the method containing the execution point
     *         is a native method
     * @throws NullPointerException if <tt>declaringClass</tt> or
     *         <tt>methodName</tt> is null
     * @since 1.5
     */
    public StackTraceElement(String declaringClass, String methodName,
                             String fileName, int lineNumber) {
        if (declaringClass == null)
            throw new NullPointerException("Declaring class is null");
        if (methodName == null)
            throw new NullPointerException("Method name is null");
 
        this.declaringClass = declaringClass;
        this.methodName     = methodName;
        this.fileName       = fileName;
        this.lineNumber     = lineNumber;
    }

    /**
     * Returns the name of the source file containing the execution point
     * represented by this stack trace element.  Generally, this corresponds
     * to the <tt>SourceFile</tt> attribute of the relevant <tt>class</tt>
     * file (as per <i>The Java Virtual Machine Specification</i>, Section
     * 4.7.7).  In some systems, the name may refer to some source code unit
     * other than a file, such as an entry in source repository.
     *
     * @return the name of the file containing the execution point
     *         represented by this stack trace element, or <tt>null</tt> if
     *         this information is unavailable.
     */

    public String getFileName() {
        return fileName;
    }

    /**
     * Returns the line number of the source line containing the execution
     * point represented by this stack trace element.  Generally, this is
     * derived from the <tt>LineNumberTable</tt> attribute of the relevant
     * <tt>class</tt> file (as per <i>The Java Virtual Machine
     * Specification</i>, Section 4.7.8).
     *
     * @return the line number of the source line containing the execution
     *         point represented by this stack trace element, or a negative
     *         number if this information is unavailable.
     */
    public int getLineNumber() {
        return lineNumber;
    }

    /**
     * Returns the fully qualified name of the class containing the
     * execution point represented by this stack trace element.
     *
     * @return the fully qualified name of the <tt>Class</tt> containing
     *         the execution point represented by this stack trace element.
     */
    public String getClassName() {
        return declaringClass;
    }

    /**
     * Returns the name of the method containing the execution point
     * represented by this stack trace element.  If the execution point is
     * contained in an instance or class initializer, this method will return
     * the appropriate <i>special method name</i>, <tt>&lt;init&gt;</tt> or
     * <tt>&lt;clinit&gt;</tt>, as per Section 3.9 of <i>The Java Virtual
     * Machine Specification</i>.
     *
     * @return the name of the method containing the execution point
     *         represented by this stack trace element.
     */
    public String getMethodName() {
        return methodName;
    }

    /**
     * Returns true if the method containing the execution point
     * represented by this stack trace element is a native method.
     *
     * @return <tt>true</tt> if the method containing the execution point
     *         represented by this stack trace element is a native method.
     */
    public boolean isNativeMethod() {
        return lineNumber == -2;
    }

    /**
     * Returns a string representation of this stack trace element.  The
     * format of this string depends on the implementation, but the following
     * examples may be regarded as typical:
     * <ul>
     * <li>
     *   <tt>"MyClass.mash(MyClass.java:9)"</tt> - Here, <tt>"MyClass"</tt>
     *   is the <i>fully-qualified name</i> of the class containing the
     *   execution point represented by this stack trace element,
     *   <tt>"mash"</tt> is the name of the method containing the execution
     *   point, <tt>"MyClass.java"</tt> is the source file containing the
     *   execution point, and <tt>"9"</tt> is the line number of the source
     *   line containing the execution point.
     * <li>
     *   <tt>"MyClass.mash(MyClass.java)"</tt> - As above, but the line
     *   number is unavailable.
     * <li>
     *   <tt>"MyClass.mash(Unknown Source)"</tt> - As above, but neither
     *   the file name nor the line  number are available.
     * <li>
     *   <tt>"MyClass.mash(Native Method)"</tt> - As above, but neither
     *   the file name nor the line  number are available, and the method
     *   containing the execution point is known to be a native method.
     * </ul>
     * @see    Throwable#printStackTrace()
     */
    public String toString() {
        return getClassName() + "." + methodName +
            (isNativeMethod() ? "(Native Method)" :
             (fileName != null && lineNumber >= 0 ?
              "(" + fileName + ":" + lineNumber + ")" :
              (fileName != null ?  "("+fileName+")" : "(Unknown Source)")));
    }

    /**
     * Returns true if the specified object is another
     * <tt>StackTraceElement</tt> instance representing the same execution
     * point as this instance.  Two stack trace elements <tt>a</tt> and
     * <tt>b</tt> are equal if and only if:
     * <pre>
     *     equals(a.getFileName(), b.getFileName()) &&
     *     a.getLineNumber() == b.getLineNumber()) &&
     *     equals(a.getClassName(), b.getClassName()) &&
     *     equals(a.getMethodName(), b.getMethodName())
     * </pre>
     * where <tt>equals</tt> is defined as:
     * <pre>
     *     static boolean equals(Object a, Object b) {
     *         return a==b || (a != null && a.equals(b));
     *     }
     * </pre>
     * 
     * @param  obj the object to be compared with this stack trace element.
     * @return true if the specified object is another
     *         <tt>StackTraceElement</tt> instance representing the same
     *         execution point as this instance.
     */
    public boolean equals(Object obj) {
        if (obj==this)
            return true;
        if (!(obj instanceof StackTraceElement))
            return false;
        StackTraceElement e = (StackTraceElement)obj;
        return e.declaringClass.equals(declaringClass) && e.lineNumber == lineNumber
            && eq(methodName, e.methodName) && eq(fileName, e.fileName);
    }

    private static boolean eq(Object a, Object b) {
        return a==b || (a != null && a.equals(b));
    }

    /**
     * Returns a hash code value for this stack trace element.
     */
    public int hashCode() {
        int result = 31*declaringClass.hashCode() + methodName.hashCode();
        result = 31*result + (fileName == null ?   0 : fileName.hashCode());
        result = 31*result + lineNumber;
        return result;
    }

    private static final long serialVersionUID = 6992337162326171013L;
}
 
分享到:
评论

相关推荐

    StackTraceElement获取方法调用栈信息实例详解

    StackTraceElement获取方法调用栈信息实例详解 StackTraceElement是Java中的一个类,它提供了获取方法调用栈信息的能力,这使得开发者可以轻松地获取当前方法的调用栈信息,从而方便地进行错误调试和日志记录。本文...

    JDK源码,整合所有内容

    - 虽然JDK源码不包含JVM本身,但它包含了很多与JVM交互的类,如`ClassLoader`、`StackTraceElement`等,通过这些可以了解到类加载和执行的细节。 9. **国际化与本地化** - `java.text`和`java.util.Locale`等类...

    日志打印工具-资源分必选-到博客中复制代码

    StackTraceElement[] sts = Thread.currentThread().getStackTrace(); if (sts == null) { return null; } for (StackTraceElement st : sts) { if (st.isNativeMethod()) { continue; } if (st....

    Java StackTraceElement实例代码

    Java中的`StackTraceElement`类是用于表示程序执行堆栈跟踪中的单个元素,它包含了类名、方法名、源文件名以及行号等关键信息。这些信息在进行问题定位、调试和日志记录时非常有用。`StackTraceElement`类通常在处理...

    LvmamaXmlKit.rar

    Error while parsing UI hierarchy XML file: null[Ljava.lang.StackTraceElement;@14b61ef4 Error while parsing UI hierarchy XML file: null[Ljava.lang.StackTraceElement;@14b61ef4

    Java自定义异常案例--ExceptionManager(java源码)

    for (StackTraceElement st:((this.getCause()==null)?this:this.getCause()).getStackTrace()){ errorMessage.append("\n\t at "); errorMessage.append(st.toString()); } alerter.showMessageDialog...

    线程跟踪者,可跟踪当前整个类调用关系图

    7. **源码分析**:如果`ThreadStackTracker`是开源的,那么如何阅读和理解源码,学习其设计模式和编程技巧。 8. **应用实例**:在实际问题排查、性能优化或并发问题诊断中,线程跟踪工具的具体使用案例。 9. **...

    LvmamaXmlKit.jar

    LvmamaXmlKit.jar APPIUM移动测试。。

    android demo,test_function_linenumber_print,android函数名和行号的打印

    StackTraceElement stackTraceElement = e.getStackTrace()[2]; String functionName = stackTraceElement.getMethodName(); int lineNumber = stackTraceElement.getLineNumber(); Log.d("TAG", "Function: " +...

    Spring Boot全局异常处理解析

    主要为大家详细介绍了Spring Boot全局异常处理的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

    Java编程实现获取当前代码行行号的方法示例

    本文主要介绍了Java编程实现获取当前代码行行号的方法,结合实例形式分析了Java基于StackTraceElement对象实现获取代码行号的相关操作技巧。 一、获取当前代码行行号的重要性 在Java编程中,获取当前代码行行号...

    一个简单的获取异常信息的例子,包括行号

    public CustomAssertionException(String message, StackTraceElement[] stackTrace) { super(message); this.stackTrace = stackTrace; } private StackTraceElement[] stackTrace; // 其他可能的方法,如...

    Log打印类的封装(android)

    StackTraceElement stackTraceElement = new Exception().getStackTrace()[2]; String className = stackTraceElement.getClassName(); int lineNumber = stackTraceElement.getLineNumber(); String threadId =...

    打印JAVA堆栈的方法

    每个`StackTraceElement`对象表示堆栈中的一个帧,包含了方法名、文件名、行号等信息。通过遍历这个`Map`,我们可以打印出任意线程的堆栈信息。 ```java private void PrintCallStack() { java.util.Map, ...

    dwr error出错时拒绝方案

    这可以将 Java 的 `StackTraceElement` 和 `Exception` 对象转换为 JavaScript 对象,提供详细的错误信息。 然而,这种解决方案存在一些限制。例如,在使用 Spring 框架时,业务逻辑层(biz/service)可能无法被...

    Android显示Log信息(带行号)

    这个方法会返回一个`StackTraceElement`数组,数组的每个元素代表调用栈中的一层。通常,索引为2的元素表示当前Log语句所在的代码行。例如: ```java Log.d("TAG", "这是带有行号的Log: " + new Exception()....

    利用Java获取文件名、类名、方法名和行号的方法小结

    首先,Java通过`StackTraceElement`类提供了获取这些信息的能力。`StackTraceElement`代表了执行堆栈中的一个元素,即一个方法调用。当抛出一个异常时,Java会自动生成一个堆栈跟踪,其中包含了导致异常的所有方法...

    Android获取当前运行的类名或者方法

    StackTraceElement[] stacks = new Throwable().getStackTrace(); String methodName = stacks[level].getMethodName(); return methodName; } public static String getCurrentClassName() { int level

    Java 实例 - 获取异常的堆栈信息源代码-详细教程.zip

    `StackTraceElement`类表示堆栈跟踪中的单个元素,包含类名、方法名、行号和源文件名等信息。可以使用这些信息来定位到出错的具体代码行。 5. **打印堆栈信息** 通常,我们会将堆栈信息打印到控制台以进行调试,...

Global site tag (gtag.js) - Google Analytics