Polly
Polly

Reputation: 11

java get accessing class name of static method

Is it possible to compute name of class which was used to access static method?

To better understand question:

class S {
    public static String method() {
        return "S";// TODO compute class name here
    }
}

class S1 extends S {
}

class S2 extends S {
}

public class Main {
    public static void main(String[] args) {
        System.out.println(S.method()); //should print S
        System.out.println(S1.method()); //should print S1
        System.out.println(S2.method()); //should print S2
    }
}

It seems that I can't use neither stacktrace nor type parameter technique.

Thanks

Upvotes: 1

Views: 591

Answers (3)

You cannot tell. It is the same method in the same class being invoked, even if you invoke it from a subclass. An IDE may suggest refactoring your code so all three instances refer to S instead of S1 or S2.

If you want to do anything like this, then consider

public static String method(Class<S> c) {
   ....
}

and invoke it with

   S.method(S2.class)

You may consider why you want to do this and if going non-static would be a help to make this easier.

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726499

You cannot do this, because neither S1.method nor S2.method exist in bytecode. The only method that is available for invocation is S.method. Compiler resolves all three calls to it, and produces identical invokestatic byte code for all three calls in your example.

Upvotes: 2

Stoat
Stoat

Reputation: 117

The question doesn't really make sense - calling method() will print S in each case - because it is the same method being called. Do you want the following?

System.out.println(S1.class.getSimpleName());

Upvotes: 0

Related Questions