Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the name of a calling class without the use of Exceptions

Tags:

java

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.

like image 611
Peeter Avatar asked Mar 21 '11 09:03

Peeter


People also ask

How do you find the throwable exception name?

To get it programmatically you can use: String exceptionClassName = e. getClass(). getName();

Can we call methods using class name?

Yes, It is allowed to define a method with the same name as that of a class. There is no compile-time or runtime error will occur.

How to get. class object from a object?

getClass() If an instance of an object is available, then the simplest way to get its Class is to invoke Object. getClass() . Of course, this only works for reference types which all inherit from Object .


1 Answers

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).

like image 191
Sean Patrick Floyd Avatar answered Oct 06 '22 01:10

Sean Patrick Floyd