user644718
user644718

Reputation:

How to get a instance of the caller class in a static method in java?

for example:

public class MyParentClass
{
  static MyParentClass AStaticMethod()
  {
    //get a new childclass instace here
    //modify this instance
    return(ChildClassInstance);
  }
}

public class AChildClass extends ParentClass {}

Is possible for AStaticMethod to get a new instace of the AChildClass when called from it (AChildClass.AStaticMethod)?

I've seen similar code using tricks like using the stack trace or throwing an exception and catching it, but I'm looking for a cleaner way to do this.

Think of AStaticMethod as a generic initializer for child classes.

I remember that I did something like it in PHP, but it relied heavily on the dynamic weak typing and reflection of the language.

Upvotes: 0

Views: 908

Answers (2)

Johan Sjöberg
Johan Sjöberg

Reputation: 49187

I suppose you could take an approach where you either wrap all your objects in a dynamic proxy or hook into the execution path using AoP. Whenever a method is invoked you could store this information in some static invocationLogging class. However, I see no clean way of achieving what you're asking.


You don't explicitly need to throw and catch an exception, you can just get it using

 StackTraceElement[] trace = Thread.currentThread().getStackTrace();

where the first element in the array should correspond to the last invoked method. E.g.,

public static void main(String[] args) {
    first();
}

public static void first() {
    second();
}

public static void second() {
    StackTraceElement[] trace = Thread.currentThread().getStackTrace();

    System.out.println(trace[0].getMethodName()); // getStackTrace
    System.out.println(trace[1].getMethodName()); // second
    System.out.println(trace[2].getMethodName()); // first
    System.out.println(trace[3].getMethodName()); // main
}

Upvotes: 0

Stan Kurilin
Stan Kurilin

Reputation: 15792

I'm looking for a cleaner way to do this.

There isn't any clean way to do this.

You should do some refactoring, like divide initializers and usage classes (like AChildClass) into separate classes.

Upvotes: 2

Related Questions