Java: get the name of the called class from a static method

I have two classes defined as follows:

class A { public static String getName(){ Class c = getCalledClass(); return c.getSimpleName(); } } class B extends A { //no methods are defined here! } 

I want to know if it is possible to create a static getCalledClass() method so that the call to A.getName() returns A and B.getName() returns B ?

Thanks.

+4
source share
4 answers

This is not possible, at least not in the general sense that you requested.

There is no B.getName() method. Although you can enter it into the code, it will be compiled with the same bytecode in A.getName() (and I think you will also get a compiler warning).

Thus, at run time, there is no way to tell how someone refers to the static method - just as there is no way to determine which names of the local variable the caller uses.

+6
source

I do not know if you can remove static or not according to your requirement. If you can remove static and use polymorphism, you can get what you want. Below is an example of the code that I tested.

 class A { public String getName(){ Class c = this.getCalledClass(); return c.getSimpleName(); } Class getCalledClass() { return A.class; } } class B extends A { Class getCalledClass() { return B.class; } } class TestApplication { public static void main(String[] args) { A objA = new A(); System.out.println(objA.getName()); A objB = new B(); System.out.println(objB.getName()); } } 
0
source

The stack trace will only contain the name of the class for which the static method is specified. Even if you call B.method() , you will see A.method() in the stack trace. Using a static circuit, you cannot reliably obtain the necessary information.

If you use non-static methods, then this will be an instance of the type you are looking for.

 public String getName() { return this.class.getSimpleName(); } 
0
source

When the javac compiler finds a call to B.getName() , it solves it there - and - then - A.getName() and puts the static call A.getName() in the byte code.

In java, there is no mechanism that can output the form used in the source code from byte code.

If you want B.getName() be another A.getName() method, you must define a method called getName() in B Since the called class will always be "B" in this method, there is no need to bypass the stack trace or other mechanisms. However, as a rule, if you think that it was important that it was to the point, it is probably best to use an object-oriented design for you.

0
source

Source: https://habr.com/ru/post/1489887/


All Articles