5

Yes, getting the class name by using an exception is a plausible solution, but I'm looking for something that is a bit more elegant.

String className = new Exception().getStackTrace()[1].getClassName();

This will be used mainly for logging purposes and making sure my cache keywords are component/caller-class specific.

3

3 Answers 3

12

a) no need to use Exception, you can do this: Thread.currentThread().getStackTrace()

b) whatever you are trying to do, don't do it that way. That sounds awful. I guess you should be looking into logging via AOP (here's a small tutorial that looks reasonable).

Sign up to request clarification or add additional context in comments.

5 Comments

There are good reasons to get the calling class. One of the common ones is to call Class.getResourceAsStream() on the caller's class rather than the method's class ("get my class's resource")
@Wheezil sure, but that sounds hacky, as most scenarios will. I'm not saying I never go the hacky way, but I prefer the "clean" way whenever I can.
Also note that the calling class.method is element [2] in the stack trace. Element [1] is the current class.method, and element[0] is Thread.getStackTrace
Agreed this is hacky. I've only ever done this for testing, if I want to centralize the load-from-resource-name into a utility method.
Yes, I also have been guilty of that, just as I use reflection a lot in tests
3
Thread.currentThread().getStackTrace()

1 Comment

By the way Thread method is the slowest, the fastest way is a custom SecurityManager as measured here: stackoverflow.com/a/2924426/1386911
3

On the Oracle JVM you can use the non-standard sun.reflect.Reflection.getCallerClass(2) . This is much faster but should only be used with care. (As it is not cross platform and could change between versions of Java)

1 Comment

It did changed between Java7u10 and u11. Beside of this it will be removed in Java8. What a pity, it was the fastest method so far (~ 100x faster then Thread.currentThread().getStackTrace()) and I see no replacement.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.