Java:判断静态方法是从实例调用还是静态调用

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

在Java中,是否可以确定静态方法是从对象实例调用还是静态调用(SomeClass.method())?

为了让您更好地了解我在说什么,请查看下面的代码:

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."
    }

}

我知道从实例调用静态方法不是好的做法,但仍然可以区分这两个调用吗?我在想 Reflection API 可能是解决这个问题的关键。

仅调用该方法是不可能的。但是,您可以从此处解释的堆栈跟踪中获得一些有用的信息 How do I find the caller of a method using stacktrace or reflection?

这将允许您使用静态方法

确定方法名称and/or调用者class

我不认为反思可以做到这一点。但是,你可以用另一种方式来实现:

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."
    }

}