Vivek
Vivek

Reputation: 2101

Exception stacktrace of Reflected method in Java

I am calling a method via reflection , which throws an exception.

However when I get the stacktrace via

StackTraceElement[] elements = Thread.currentThread().getStackTrace();

i don't get the entire stack trace upto the reflected method. It gets the stack trace only uptil my method which implements reflection.

The reflected class is in a different project altogether.

EDIT : Adding code snippet

Project A

Class ReflectionImpl {

   public void callMethodsviaReflection{
     try{
              // Reflection code to call the method

         }catch(InvocationTargetException iTE){

           StringBuilder errorLogBuilder = new StringBuilder();
            errorLogBuilder.append(ex.toString());
            errorLogBuilder.append("\n");

            StackTraceElement[] elements = Thread.currentThread().getStackTrace();

             for (int i=0;i<elements.length;i++) {

                 errorLogBuilder.append((elements[i].toString()));
                 errorLogBuilder.append("\n");
             }

            System.out.println(errorLogBuilder.toString());
        }
    }
}

Project B --> References Project A in Eclipse

Class ReflectedClass{

 List<String> nameList = null;

 public void reflectedMethod(){

     nameList.add("Hello");
    }      
}

Upvotes: 0

Views: 684

Answers (1)

Perception
Perception

Reputation: 80603

At the particular point where you are calling:

StackTraceElement[] elements = Thread.currentThread().getStackTrace();

your 'reflective invocation' has already been completed, which is reflected in the call stack you get back from the call. Sounds more like you want:

iTE.getCause().getStackTrace();

Which will give you the call stack up to and including the method that actually threw the exception.

Upvotes: 8

Related Questions