David Watson
David Watson

Reputation: 2039

Access The Type of the Containing Class of a Static Method in Java

So I am working on a compiler from the ground up, but am stumbling over how to figure out which class a static method was called through. Take a look at the example:

public abstract class Token {

public TokenType type;

  public Token() {
        super();
        this.type = TokenType.getInstance(this.getClass());
  }
  public static TokenType type() {
        Class<? extends Token> t = null; //WHAT SHOULD GO HERE
        return TokenType.getInstance(t);
  } 
}

If I then have two classes that inherit from Token

public class TestToken extends Token {
  public TestToken() {
    super()
  }
}

and

public class TestToken2 extends Token {
  public TestToken2() {
    super()
  }
}

How do I call TestToken.type() and TestToken2.type(), and have the static method know through which it was called? Specifically, I need access to the Class object of each. Is this even possible?

Note I know that I could hard code in the class of each, but that seems like unnecessary work, and like less fun :)

Answer Hello people from the future. As Niels thoroughly explains below, this isn't possible. You'll need to find another way.

Upvotes: 0

Views: 150

Answers (1)

Niels Bech Nielsen
Niels Bech Nielsen

Reputation: 4859

You wouldn't inherit the static method, so you wouldn't actually call TestToken.type() nor TestToken2.type()... Only Token.type() would work. You would have to inject specific type in another way.

With the simplest of demonstration (Having also added a dynamic method in Token.java):

public class Main {
public static void main(String[] args) {
   new Token().dynamicType();
   new TestToken().dynamicType();

   Token.type();
   TestToken.type();

}}

Where each method prints it stacktrace:

Hello Dynamic world
java.lang.Exception
    at Token.dynamicType(Token.java:4)
    at Main.main(Main.java:3)
Hello Dynamic world
java.lang.Exception
    at Token.dynamicType(Token.java:4)
    at Main.main(Main.java:4)
Hello Static world
java.lang.Exception
    at Token.type(Token.java:3)
    at Main.main(Main.java:6)
Hello Static world
java.lang.Exception
    at Token.type(Token.java:3)
    at Main.main(Main.java:7)

Update:

Added the bytecode for the method dispatch:

Code:
 0: new #2; //class Token
 3: dup
 4: invokespecial   #3; //Method Token."<init>":()V
 7: invokevirtual   #4; //Method Token.dynamicType:()V
 10:    new #5; //class TestToken
 13:    dup
 14:    invokespecial   #6; //Method TestToken."<init>":()V
 17:    invokevirtual   #7; //Method TestToken.dynamicType:()V
 20:    invokestatic    #8; //Method Token.type:()V
 23:    invokestatic    #9; //Method TestToken.type:()V
 26:    return

Upvotes: 1

Related Questions