问题描述
我有2个类A和B,其中B扩展了A。两个类都有一个静态变量x。在类A中定义了一个访问x的静态方法。当我从main用B调用方法时,有什么方法可以知道函数的调用者吗?有了该调用方的类名,我可以使用反射来从类B中获取x的值。
public class Test {
public static void main(String[] args) throws Exception {
A a = new A();
B b = new B();
b.amthu();
}
private static class A {
public static String x = "static string from A";
public static void amthu() throws NoSuchFieldException,illegalaccessexception {
System.out.println(/* what can be the line here?*/);
}
}
private static class B extends A {
public static String x = "static string from B";
}
}
我在python中有类似的代码,因为类方法以cls作为参数,所以工作正常,但是静态方法没有这种东西,而在Java中,我只知道静态方法,因此无法从sub访问x的值B级。
class A:
x = "static value of A"
@classmethod
def amthu(cls):
print(getattr(cls,"x",None))
class B(A):
x = "static value of B"
a = A()
b = B()
b.amthu()
解决方法
您可以执行instanceof检查,然后打印B.x或A.x
如果(此A的实例) 系统输出println A.x 其他 System.out.println B.x
, A.amthu()
方法无法检测到使用类型B
的变量调用了它。
Java中的静态方法具有诸如此类的基本限制。这些限制是为什么您看不到Java中使用太多静态方法的原因。尤其不建议使用b.amthu()
之类的对象实例调用静态方法,因为这会引起混乱-另请参见Why isn't calling a static method by way of an instance an error for the Java compiler?
您可以通过将所需的类作为变量传递给A.amthu来解决此问题:
// call method
A.amthu(B.class);
// method declaration in A
static void amthu(Class<? extends A> klass) { ... }
或者,也许您可以重新编写代码以避免完全使用静态字段和方法。在不知道您要在这里做什么的情况下,不可能告诉您会是什么样。