1

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

6
  • @DVarga That's an entirely different question. Commented Jan 24, 2017 at 12:41
  • There's getName(), but it won't solve this specific case. Commented Jan 24, 2017 at 12:45
  • 1
    Do you really want this or do you try to solve a different issue with this? What is your purpose for this feature? Commented Jan 24, 2017 at 12:45
  • In reality I have enum S1 and enum S2 and I want to store as much code as possible into interface S. To overcome imperfections of java enums I need to do it. The other solution is to use non-static default method but then I send to method not only class name but also irrelevant enum instance. Commented Jan 24, 2017 at 12:55
  • And why do you have two different enums when they are that similar? Maybe it isn't a good idea to use enums if you have trouble with them? Commented Jan 24, 2017 at 13:01

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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());

1 Comment

And how should OP know that it is S1 and not S2? You should add that part in your answer.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.