starwarswii
starwarswii

Reputation: 2417

Java: determine if a static method is called from an instance or statically

In Java, is it possible to determine whether a static method is called from either an instance of the object, or statically (SomeClass.method())?

To give you an a better idea of what I'm talking about, take look at this code below:

public class SomeClass {

    public static void staticMethod() {

        if (/*called from instance*/) {
            System.out.println("Called from an instance.");
        } else if (/*called statically*/){
            System.out.println("Called statically.");
        }
    }

    public static void main(String[] args) {
        new SomeClass().staticMethod();//prints "Called from an instance."
        SomeClass.staticMethod();//prints "Called statically."
    }

}

I understand it isn't good practice to call a static method from an instance, but still, is it possible to differentiate between these two calls? I was thinking that the Reflection API probably holds the key to this.

Upvotes: 2

Views: 815

Answers (2)

expoter
expoter

Reputation: 1640

I don't think reflection can make this. But, you can make it in another way:

public class SomeClass {

    public static void staticMethod(boolean isStaticCall) {

        if (!isStaticCall) {
            System.out.println("Called from an instance.");
        } else{
            System.out.println("Called statically.");
        }
    }

    public static void main(String[] args) {
        new SomeClass().staticMethod(false);//prints "Called from an instance."
        SomeClass.staticMethod(true);//prints "Called statically."
    }

}

Upvotes: 1

Rohan Verma
Rohan Verma

Reputation: 26

That is not possible by just calling the method. However you can gain some useful information from the stacktrace explained here How do I find the caller of a method using stacktrace or reflection?

This will allow you to determine the method name and/or caller class using the static method

Upvotes: 1

Related Questions