有没有办法在被调用的 class 的方法中访问 variables/fetch 调用者 class 的赋值?

Is there a way to access the variables/fetch the assigned values of the caller class in a method of the called class?

这与问题类似: Is there a way to access the variables of the calling class in a method? 但我不太能得到确切的答案。 我想做什么:

class A{
    m()
    {
        int a=8;
        new B.m1();

    }
}

class B{
    m1()
    {
         //Print the value of a of class A (i.e 8) here     
    }
}

约束: class A 中的任何内容都不应 changed.Changes 仅在 class B 中制作! (比如把B.m1(this)放在classA等)

不,这是不可能的。 特别是 因为a 是局部变量。

如果 a 是一个字段,那么 可能 可以通过一些反射/堆栈跟踪 hack 来解决这个问题。

了解 'this' 关键字。但在这里这是不可能的,因为你正在谈论一个局部变量,其范围只是方法 m()

鉴于 'a' 的范围,将其作为参数传递是访问它的唯一方法。