mardi 22 août 2017

How to find the instance in Java that called my static method so I can call methods on that instance? [duplicate]

This question already has an answer here:

I think what I need is AOP but I can't use AOP there. Need some neat workaround from a creative mind.

Problem is simple:

public class Hello {

    public void myMethod() {

        MyClass.myStaticMethod();

    }
}

public class MyClass {

    public static void myStaticMethod() {

        Object callerInstance = getTheInstanceWhoCalledMe();

        if (callerInstance instanceof Animal) {
            Animal a = (Animal) callerInstance;
            System.out.println(a.eat());
        }
    }

    public static Object getTheInstanceWhoCalledMe() {

        // ???????? Any creative genius out there?
    }
}





Aucun commentaire:

Enregistrer un commentaire