java获取访问静态方法的类名

时间:2017-01-24 12:39:52

标签: java methods static access

是否可以计算用于访问静态方法的类名?

更好地理解问题:

class S {
    public static String method() {
        return "S";// TODO compute class name here
    }
}

class S1 extends S {
}

class S2 extends S {
}

public class Main {
    public static void main(String[] args) {
        System.out.println(S.method()); //should print S
        System.out.println(S1.method()); //should print S1
        System.out.println(S2.method()); //should print S2
    }
}

似乎我既不能使用堆栈跟踪也不能使用类型参数技术。

由于

3 个答案:

答案 0 :(得分:2)

您无法执行此操作,因为字节码中不存在S1.methodS2.method。唯一可用于调用的方法是S.method。编译器会解析对它的所有三个调用,并为您示例中的所有三个调用生成相同的invokestatic字节代码。

答案 1 :(得分:0)

问题没有意义 - 调用method()会在每种情况下都打印S - 因为它是被调用的相同方法。你想要以下吗?

System.out.println(S1.class.getSimpleName());

答案 2 :(得分:0)

你无法分辨。即使从子类调用它,它也会在同一个类中被调用。 IDE可能会建议重构您的代码,以便所有三个实例都引用S而不是S1或S2。

如果您想做这样的事情,请考虑

public static String method(Class<S> c) {
   ....
}

并使用

调用它
   S.method(S2.class)

您可能会考虑为什么要这样做,如果进行非静态操作会有助于简化这一过程。

相关问题