George Vince
George Vince

Reputation: 180

How to distinguish between which class calls a method?

I'm trying to determine which class has called a method, is there a more elegant way to do this?

public void testMethod(Class c) {
    String className = c.getCanonicalName();
    int splitAfter = className.lastIndexOf(".");
    String parsedName = className.substring(splitAfter + 1,className.length());

    if (parsedName.contains("ClassA")) {
    // Do class A specific stuff
    } else if (parsedName.contains("ClassB")) {
    // Do class B specific stuff
    } else if (parsedName.contains("ClassC")) {
    // Do Class C specific stuff
    }
}

Called with

testMethod(this.getClass)

Upvotes: 0

Views: 83

Answers (2)

MaxZoom
MaxZoom

Reputation: 7753

I believe you can get the caller class from the stack trace:

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

It is a stack, so the previous Class should be at index 1.

See documentation for more info on StackTraceElement.

Upvotes: 0

Is there a reason you can't do:

if(c == ClassA.class) {
    // do stuff
} else if(c == ClassB.class) {
    // do stuff
} else if(c == ClassC.class) {
    // do stuff
}

?

No string manipulation required!

Upvotes: 1

Related Questions