Get the name of a calling class without the use of Exceptions
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).
How can I get the caller class object from a method in java?
Get the classname using the code of your linked question: How to get the caller class in Java
Then use the classname to retrieve the class, using code from here: Getting class by its name
Complete code:
String callerName = Thread.currentThread().getStackTrace()[2].getClassName();
try {
Class<?> caller = Class.forName(callerName);
// Do something with it ...
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
(community answer, since only mix of existing answers).
Java - get the current class name?
The "$1" is not "useless non-sense". If your class is anonymous, a number is appended.
If you don't want the class itself, but its declaring class, then you can use getEnclosingClass()
. For example:
Class<?> enclosingClass = getClass().getEnclosingClass();
if (enclosingClass != null) {
System.out.println(enclosingClass.getName());
} else {
System.out.println(getClass().getName());
}
You can move that in some static utility method.
But note that this is not the current class name. The anonymous class is different class than its enclosing class. The case is similar for inner classes.
Get caller class and method name
Unfortunately, there is no non-expensive method to do this. There is a Java Enhancement Proposal to add a better alternative, but this doesn't help unless you can wait until Java 9 (and it isn't guaranteed to be included anyway).
On the other hand, is this really a hotspot in your code? This should only matter if it's called in a loop, and in this case you probably can call it once and cache the result.
Get class name in a static way in Java 8
Example for getting the class name of the calling class in a static way from another class:
public class Main {
public static void main(String[] args) {
example();
}
public static void example() {
B b = new B();
b.methodB();
}
}
class B {
public void methodB(){
System.out.println("I am methodB");
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
StackTraceElement element = stackTrace[2];
System.out.println("I was called by a method named: " + element.getMethodName());
System.out.println("That method is in class: " + element.getClassName());
}
}
Example for getting the fully qualified class name in static way:
MyClass.class.getName();
How to get a caller class of a method
This is easily done with Thread.currentThread().getStackTrace()
.
public static void main(String[] args) {
doSomething();
}
private static void doSomething() {
System.out.println(getCallerClass());
}
private static Class<?> getCallerClass() {
final StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
String clazzName = stackTrace[3].getClassName();
try {
return Class.forName(clazzName);
} catch (ClassNotFoundException e) {
e.printStackTrace();
return null;
}
}
[3]
is used because [0]
is the element for Thread.currentThread()
, [1]
is for getCallerClass
, [2]
is for doSomething
, and finally, [3]
is main
. If you put doSomething
in another class, you'll see it returns the correct class.
Is there any way to know the caller class name?
You can use Thread.currentThread().getStackTrace()
to get a stack trace, then iterate through it to find which method is above yours in the stack.
For example (totally made up stack here), you might have a stack like this:
main()
|- Foo()
|- Bar()
|- MyFunction()
|- getStackTrace()
|- captureJavaThreadStack(...)
Starting from the bottom, you iterate up until you hit the getStackTrace()
method. You then know that the calling method is two methods up from that position, i.e. MyFunction()
called getStackTrace()
, which means that MyFunction()
will always be above getStackTrace()
, and whatever called MyFunction()
will be above it.
You can use the getClassName()
method on the StackTraceElement
class to pull out the class name from the selected stack trace element.
Docs:
http://docs.oracle.com/javase/6/docs/api/java/lang/Thread.html#getStackTrace%28%29
http://docs.oracle.com/javase/6/docs/api/java/lang/StackTraceElement.html
Related Topics
Get List of JSON Objects with Spring Resttemplate
How Do Synchronized Static Methods Work in Java and How to Use It for Loading Hibernate Entities
Determine Which Jar File a Class Is From
Gson Throws Malformedjsonexception
Why Doesn't Java Map Extend Collection
How to Get a Date Without Time in Java
How to Turn a String into a Inputstreamreader in Java
How to Connect to SQL Server Using Windows Authentication from Java Ee Webapp
Move/Copy File Operations in Java
Java Lambdas 20 Times Slower Than Anonymous Classes
Green Threads VS Non Green Threads
What Is Recommended Way for Spawning Threads from a Servlet in Tomcat
How to Find Nth Occurrence of Character in a String