有没有办法在方法中访问调用类的变量?

目前我有一个类调用不同类的静态方法。 我想要做的是让静态方法改变调用类的变量,这可能吗?

示例代码:

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语句。

您可以this参数作为参数传递给第二个函数。

 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 } } 

如果aClass不公开该变量,则不会。 这就是封装和信息隐藏的含义:如果类的设计者将变量设为私有,那么只有拥有它的组件才能修改或访问它。

当然,Java中的一个肮脏的小秘密就是reflection可以让你绕过任何私人限制。

但你不应该诉诸于此。 您应该适当地设计您的课程并尊重他人的设计。

你应该在othClass中给出静态方法exClass的实例,比如othClass.aMethod(this),那么你可以改变那个实例的变量,或者如果你不需要实例就让变量变为静态