如何获取方法的调用者类 [英] How to get a caller class of a method

查看:86
本文介绍了如何获取方法的调用者类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何知道哪个类称为方法?

How do I know which class called a method?

class A {
   B b = new B();

   public void methodA() {
    Class callerClass = b.getCallerCalss(); // it should be 'A' class
   } 
}

class B {
 public Class getCallerCalss() {
   //... ???
   return clazz;
 }
}


推荐答案

这很容易用 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] 是因为 [0] Thread.currentThread(),<$ c的元素$ c> [1] 适用于 getCallerClass [2] 适用于 doSomething ,最后, [3] main 。如果你把 doSomething 放在另一个类中,你会看到它返回正确的类。

[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.

这篇关于如何获取方法的调用者类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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