如何找出什么类在Java中称为方法? [英] how to figure out what class called a method in java?

查看:74
本文介绍了如何找出什么类在Java中称为方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何找出哪个类调用了我的方法而不将任何变量传递给该方法?
假设我们有这样的东西:

How do I figure out what class called my method without passing any variable to that method? let's say we have something like this:

Class A{}
Class B{}
Class C{
public void method1{}
System.out.print("Class A or B called me");
}

假设A类的实例调用了C类的实例,当类A调用类C method1方法时,我希望它打印类似类A调用我的内容,而当类B调用它以打印类B调用我的内容时。

let's say an instance of Class A calls an instance of class C and the same for class B. When class A calls class C method1 method, I want it to print something like "Class A called me", and when class B called it to print "Class B called me".

推荐答案

并没有真正简单的方法,因为通常情况下,一个方法不需要而且不需要在哪里它被称为。如果您编写方法以使其根据调用源的不同而表现不同,那么您的程序很快就会变成难以理解的混乱。

There's no really easy way to do this, because normally a method doesn't and shouldn't need to care from where it is called. If you write your method so that it behaves differently depending on where it was called from, then your program is quickly going to turn into an incomprehensible mess.

但是,这是一个示例:

public class Prut {
    public static void main(String[] args) {
        example();
    }

    public static void example() {
        StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
        StackTraceElement element = stackTrace[2];
        System.out.println("I was called by a method named: " + element.getMethodName());
        System.out.println("That method is in class: " + element.getClassName());
    }
}

这篇关于如何找出什么类在Java中称为方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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