有没有办法在方法中访问调用类的变量? [英] Is there a way to access the variables of the calling class in a method?
本文介绍了有没有办法在方法中访问调用类的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
目前,我有一个正在调用其他类的静态方法的类。但是我想做的是让静态方法更改调用类的变量,这可能吗?
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
}
}
这篇关于有没有办法在方法中访问调用类的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文