0

I want to customize hashcode of StackTraceElement class . My problem is how to use this new customized class instead of default StackTraceElement class of JVM.

Saurabh Agarwal
  • 323
  • 2
  • 6
  • 16

2 Answers2

2

I want to customize the StackTraceElement class by extending it

StackTraceElement is final and hence can not be extended.

If you (for whatever reason) want to customize the way a stack trace is printed, you can implement a utility method which takes the Throwable and then uses the various methods from StackTraceElement to create your own layout, something like

public static void printCustomizedTrace(Throwable t) {
   for(StackTraceElement e : t.getStackTrace()) {
      System.err.println(" => " + e.getFileName() + ":" + e.getLineNumber());
   }
}

You could also use delegation and create a list of CustomStackTraceElements, and implement additional logic (like different hashmap()) in the CustomStackTraceElement class:

public static List<CustomStackTraceElement> getCustomizedStackTrace(Throwable t) {
   List<CustomStackTraceElement> result = new ArrayList<>();

   for(StackTraceElement e : t.getStackTrace()) {
      result.add(new CustomStackTraceElement(e));
   }

   return result;
}
Andreas Fester
  • 36,091
  • 7
  • 95
  • 123
0

StackTraceElement is a final class. Final classes can't be extended.

Look at this adn this

Community
  • 1
  • 1
Davor Pecet
  • 171
  • 2
  • 6