我是靠谱客的博主 光亮马里奥,最近开发中收集的这篇文章主要介绍java 获得调用者类名,如何在Java中获取调用者类,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

I want to get the caller class of the method, i.e.

class foo{

bar();

}

In the method bar, I need to get the class name foo, and I found this method:

Class clazz = sun.reflect.Reflection.getCallerClass(1);

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

Access restriction: The method getCallerClass() from the type

Reflection is not accessible due to restriction on required library

C:Program FilesJavajre7librt.jar

Are there any other choices?

解决方案

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

StackTraceElement ste = stElements[i];

if (!ste.getClassName().equals(KDebug.class.getName()) && ste.getClassName().indexOf("java.lang.Thread")!=0) {

return ste.getClassName();

}

}

return null;

}

}

If you call KDebug.getCallerClassName() from bar(), you'll get "foo".

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

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 获得调用者类名,如何在Java中获取调用者类的全部内容,希望文章能够帮你解决java 获得调用者类名,如何在Java中获取调用者类所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(46)

评论列表共有 0 条评论

立即
投稿
返回
顶部