比如我写了一个类C1,然后用类C2的一方方法F2调用C1的方法F1.
在F1中如何知道是C2的F2在调用它呢,如何输出调用它的类与类的方法.用this.getSupperClass好像不行.得到的是父类.

解决方案 »

  1.   

    获取当前执行线程的Stack,取到的是一个数组,从头开始找到你当前执行的方法对应的一个数组元素,再它的下一个就是调用这个方法的方法了.
      

  2.   

    是不是这样?
    package pack;public class ThreadTest{
    public static void main(String[] args) {
    b b1 = new b();
    b1.method();
    System.out.println("*******************");
    runMethod();
    }

    public static void runMethod() {
    new b().method();
    }
    }class b{
    public void method() {
    try {
    Thread thr = Thread.currentThread();
    StackTraceElement[] ele = thr.getStackTrace();

    for (StackTraceElement e: ele) {
    System.out.print("类:"+e.getClassName());
    System.out.println("调用"+e.getMethodName()+"方法");
    System.out.println("");
    }
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
    }
      

  3.   

    楼上的还可以.把所有的过程都弄出来,但是还是不怎么好
    不知JAVA里有没有这类函数直接可以找到调用的类?
      

  4.   

    貌似没有 
    public class Test {
    public static void main(String[] args) {
    Test test = new Test();
    test.go();
    } public void go() {
    new MethodClass().getMethodName();
    }
    }class MethodClass {
    public void getMethodName() {
    try {
    Thread thr = Thread.currentThread();
    StackTraceElement[] ele = thr.getStackTrace();
    System.out.println(ele[2].getClassName() + "." + ele[2].getMethodName());
    }
    catch (Exception e) {
    e.printStackTrace();
    }
    }
    }
      

  5.   

    使用RTTI信息,其中有个instanceof 和 isinstance可以用来判断运行时调用的类类型
      

  6.   

    楼上说下具体用法,RTTI怎么用?