1

Lets say, I have

public class ClassA {
    public static void main(String[] args) {
        ClassB.methodB();
    }
}

and I'm calling a static function of another class

public class ClassB{
    public static void methodB() {
        System.out.Println("<I want to print the classname of classA>");
    }
}

How do I achieve this?

rodrigoap
  • 7,405
  • 35
  • 46
  • 5
    Is that really necessary? This seems like a hacky XY problem. Why do you need this? – Carcigenicate Dec 08 '17 at 23:32
  • 1
    you could use the stackwalker comming with java 9 https://docs.oracle.com/javase/9/docs/api/java/lang/StackWalker.html and get one "step back" in your stack .. but thats quite dirty ;-) – IEE1394 Dec 08 '17 at 23:58
  • Well, I'm trying to use Log4j and I don't want to create the static Logger object in every class. So I have created a BaseLogger class that extends Logger (Log4j) with some custom static logging functions. When I call these functions that I have created (in BaseLogger class) from another class, they are logging the classname of BaseLogger but what I wanted to print is calling classname. – Sumanth_Nyx Dec 14 '17 at 15:05

1 Answers1

1

You can't really (you could throw an exception and dig through the stack trace, but that is very slow and unnecessary).

Instead ask yourself the question why you think you need that? Is it for logging purposes?

What does methodB need to know to perform its job. If it needs to know something, it should just take a parameter and decide what to do based on that.

Jochen Bedersdorfer
  • 4,093
  • 24
  • 26