aryaxt
aryaxt

Reputation: 77596

Java - Loop through stack trace and get class and method instance?

I am trying to loop through the stack-trace and check to see if a specific annotation exists on any of those methods or not. The following code initialized the correct class, but when I call getMethodName I get NoSuchMethodException. Any idea why it's throwing this exception?

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

for (StackTraceElement element : stackTraceElements) {

    try {   
        Class<?> clazz = Class.forName(element.getClassName());
        Method method = element.getClass().getDeclaredMethod(element.getMethodName());
        cache = method.getAnnotation(Cache.class);
        break;
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}

Upvotes: 0

Views: 4639

Answers (2)

BevynQ
BevynQ

Reputation: 8259

Calling getMethod or getDeclaredMethod requires matching parameter types to return a result. You can use getMethods or getDeclaredMethods and do a method name comparison.

The downside with this is that

public void a()

and

public void a(int i)

will both yield matches if you are looking for method a.

public void dumpTrace(){
    StackTraceElement[] stackTraceElements = Thread.currentThread()
        .getStackTrace();

    for (StackTraceElement element : stackTraceElements) {

        try {
            Class<?> clazz = Class.forName(element.getClassName());
            System.out.println("Looking for " + element.getMethodName() + " in class " + clazz);
            for (Method method : clazz.getMethods()){
                if(method.getName().equals(element.getMethodName())){
                    System.out.println("Possible match : " + method);
                }
            }
            for (Method method : clazz.getDeclaredMethods()){
                if(method.getName().equals(element.getMethodName())){
                    System.out.println("Possible match : " + method);
                }
            }
        } catch (Exception e) {
            //  oops do something here
        }
    }    
}

Upvotes: 2

jend
jend

Reputation: 106

Could be that you're calling getClass() on StackTraceElement which returns... StackTraceElement instead of the class of the execution point represented by the stack trace element.

StackTraceElement provides a getClassName() method you could use that one instead.

Upvotes: 3

Related Questions