How to get the name of the calling class in Java?

Solution 1:

Easiest way is the following:

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

But in real there should be no need for this, unless for some logging purposes, because this is a fairly expensive task. What is it, the problem for which you think that this is the solution? We may come up with -much- better suggestions.

Edit: you commented as follows:

basically i'am trying to do a database Layer, and in Class A i will create a method that will generate sql statements, such statements are dynamically generated by getting the values of all the public properties of the calling class.

I then highly recommend to look for an existing ORM library, such as Hibernate, iBatis or any JPA implementation to your taste.

Solution 2:

Java 9: Stack Walking API

JEP 259 provides an efficient standard API for stack walking that allows easy filtering of, and lazy access to, the information in stack traces. First off, you should obtain an instance of StackWalker:

import static java.lang.StackWalker.Option.RETAIN_CLASS_REFERENCE;
// other imports

StackWalker walker = StackWalker.getInstance(RETAIN_CLASS_REFERENCE);

After that you can call the getCallerClass() method:

Class<?> callerClass = walker.getCallerClass();

Regardless of how you configured the StackWalker instance, the getCallerClass method will ignore the reflection frames, hidden frames and those are related to MethodHandles. Also, this method shouldn't be called on the first stack frame.

Solution 3:

Perhaps for your use case it would make sense to pass the class of the caller into the method, like:

public class A { public void foo(Class<?> c) { ... } }

And call it something like this:

public class B { new A().foo(getClass() /* or: B.class */ ); }

Solution 4:

foo() is private, so the caller will always be in class A.