如何在 Java 中获取调用者类 [英] How to get the caller class in Java

查看:57
本文介绍了如何在 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);

然而,即使 getCallerClasspublic,当我尝试调用它时 Eclipse 说:

However, even though getCallerClass is public, when I try to call it Eclipse says:

访问限制:方法getCallerClass()来自类型由于所需库的限制,无法访问反射C:Program FilesJavajre7lib t.jar

Access restriction: The method getCallerClass() from the type Reflection is not accessible due to restriction on required library C:Program FilesJavajre7lib t.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;
     }
}

如果你从 bar() 调用 KDebug.getCallerClassName(),你会得到 "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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆