如何在Java中获取调用者类 [英] How to get the caller class in Java
问题描述
我想得到该方法的调用者类,即
I want to get the caller class of the method, i.e.
class foo{
bar();
}
在方法栏中,我需要获取班级名称 foo
,我发现了这个方法:
In the method bar, I need to get the class name foo
, and I found this method:
Class clazz = sun.reflect.Reflection.getCallerClass(1);
但是,即使 getCallerClass
public
,当我尝试调用它时Eclipse说:
However, even though getCallerClass
is public
, when I try to call it Eclipse says:
访问限制:方法getCallerClass ()类型
由于对所需库的限制而无法访问反射
C:\Program Files \ Java \ jre7 \lib \ t.jar
Access restriction: The method getCallerClass() from the type Reflection is not accessible due to restriction on required library C:\Program Files\Java\jre7\lib\rt.jar
还有其他选择吗?
推荐答案
你可以生成堆栈跟踪并使用 StackTraceElements 。
You can generate a stack trace and use the informations in the StackTraceElements.
例如,实用程序类可以返回调用类名称:
For example an utility class can return you the calling class name :
public class KDebug {
public static String getCallerClassName() {
StackTraceElement[] stElements = Thread.currentThread().getStackTrace();
for (int i=1; i<stElements.length; i++) {
StackTraceElement ste = stElements[i];
if (!ste.getClassName().equals(KDebug.class.getName()) && ste.getClassName().indexOf("java.lang.Thread")!=0) {
return ste.getClassName();
}
}
return null;
}
}
如果你打电话给 KDebug。 getCallerClassName()
从 bar()
,你将得到foo
。
If you call KDebug.getCallerClassName()
from bar()
, you'll get "foo"
.
现在假设您想知道调用 bar
的方法的类(这更有趣,也许你真的是什么通缉)。您可以使用此方法:
Now supposing you want to know the class of the method calling bar
(which is more interesting and maybe what you really wanted). You could use this method :
public static String getCallerCallerClassName() {
StackTraceElement[] stElements = Thread.currentThread().getStackTrace();
String callerClassName = null;
for (int i=1; i<stElements.length; i++) {
StackTraceElement ste = stElements[i];
if (!ste.getClassName().equals(KDebug.class.getName())&& ste.getClassName().indexOf("java.lang.Thread")!=0) {
if (callerClassName==null) {
callerClassName = ste.getClassName();
} else if (!callerClassName.equals(ste.getClassName())) {
return ste.getClassName();
}
}
}
return null;
}
是否用于调试?如果没有,可能会有更好的解决方案来解决您的问题。
Is that for debugging ? If not, there may be a better solution to your problem.
这篇关于如何在Java中获取调用者类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!