Friday 28 February 2014

How to create a stack trace element

Java provides StackTraceElement class to create stack trace element and to extract the details from stack trace element.

By using the constructor provided by the class StackTraceElement, we can create StackTraceElement.

public StackTraceElement(String declaringClass,
String methodName,
String fileName,
int lineNumber)

declaringClass - the fully qualified name of the class containing the execution point represented by the stack trace element

methodName - the name of the method containing the execution point represented by the stack trace element

fileName - the name of the file containing the execution point represented by the stack trace element, or null if this information is unavailable

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

Example
class StackTraceEx{
 static void show(){
  String className = "StackTraceEx";
  String methodName = "show";
  String fileName = "StackTraceEx.java";
  int lineNum = 9;
  StackTraceElement s1 = new StackTraceElement(className, methodName, fileName, lineNum);
  System.out.println(s1);
 }

 static void print(){
  show();
 }

 public static void main(String args[]){
  StackTraceEx obj1 = new StackTraceEx();
  print();
 }
}
   
Output
StackTraceEx.show(StackTraceEx.java:9)
  

Stack trace Element                                                 Extract information from stack trace element                                                 Home

No comments:

Post a Comment