有没有办法在方法中访问调用类的变量?
问题描述:
目前,我有一个正在调用其他类的静态方法的类。但是我想做的是让静态方法更改调用类的变量,这可能吗?
At present I have a class that is calling the static method of a different class. What I am trying to do however is have the static method change a variable of the calling class, is that possible?
示例代码:
public class exClass {
private int aVariable;
public exClass() {
othClass.aMethod();
}
}
public class othClass {
static void aMethod() {
// stuff happens, preferably stuff that
// allows me to change exClass.aVariable
}
}
所以我想知道的是,是否有一种方法可以访问调用othClass的exClass实例的aVariable。显然,除了使用return语句。
So what I would like to know is, if there is a way to access aVariable of the instance of exClass that is calling othClass. Other than using a return statement, obviously.
答
您可以将 this
作为参数传递给第二个函数。
You can pass this
as a parameter to the second function.
public class exClass {
public int aVariable;
public exClass()
{
othClass.aMethod(this);
}
}
public class othClass{
static void aMethod(exClass x)
{
x.aVariable = 0; //or call a setter if you want to keep the member private
}
}