【问题标题】:Is there a way to access the variables of the calling class in a method?有没有办法在方法中访问调用类的变量?
【发布时间】:2012-02-22 14:21:23
【问题描述】:

目前我有一个类正在调用另一个类的静态方法。然而,我想要做的是让静态方法更改调用类的变量,这可能吗?

示例代码:

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 实例的变量。显然,除了使用 return 语句。

【问题讨论】:

  • 嗯...你为什么要这个? return 语句有什么问题?
  • 代码只是示例性的。我已经在退货了。由于我使用的类都是静态的,很明显我不能只将变量保存在类本身中并编写一个get方法来获取我想要的信息给类调用。
  • 这可能是一个例子,但我不会称之为典范。
  • 啊,好吧,英语不是我的第一语言。用我的语言这么说更有意义! ;)

标签: java class static


【解决方案1】:

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

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

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

【讨论】:

  • 但是如果我公开一个变量,我将如何访问它?
  • 当然,通过引用指向拥有对象的点表示法。
【解决方案2】:

您可以将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
   }
}

【讨论】:

    【解决方案3】:

    你应该给othClass中的静态方法一个exClass的实例,比如othClass.aMethod(this),然后你可以改变那个实例的变量,或者如果你不需要实例,把变量设为静态

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-01
      • 2023-03-29
      • 2013-11-24
      • 1970-01-01
      • 2023-02-21
      • 1970-01-01
      • 1970-01-01
      • 2012-03-01
      相关资源
      最近更新 更多