Java – Gets the current class object

Gets the current class object… here is a solution to the problem.

Gets the current class object

I have three classes: A、B、C。

    In both class B and C,

  1. I have a static string variable “name” that contains the names of classes B and C, like –
 class B
     {
     static name;
     public static void main(String args[])
     {
     name="Class B";
     A.getName();
     }
  1. I’m calling the getName method of class A from classes B and C. Class A is as follows:

class A
{

getName()
{
System.out.println(this class called me);
}
}

Class C is:

 class C
     {
     static name;
     public static void main(String args[])
     {
     name="Class C";
     A.getName();
     }

Now my question is, what code should I use instead of “this class calls me” in class A so I can get the name of the class that called A! I hope I’m clear!!

Solution

Your A.getName method has no way of knowing which class’s code called it. You must pass that information to it.

Well, it’s not strictly true, you can figure it out by generating a stack trace and examining it. But this is a very bad idea. In general, if a method needs to know something, you either A) make it part of an instance with that information as instance data, or B) pass information to it as a parameter.

Related Problems and Solutions