Is there a way to access the variables of the call

2019-05-23 00:29发布

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?

Example code:

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

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.

3条回答
欢心
2楼-- · 2019-05-23 01:05

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
   }
}
查看更多
迷人小祖宗
3楼-- · 2019-05-23 01:14

you should gave the static method in othClass the instance of exClass like othClass.aMethod(this), then you can change the variable of that instance, or make the variable static if you dont need an instance

查看更多
叼着烟拽天下
4楼-- · 2019-05-23 01:18

Not if aClass doesn't expose that variable. This is what encapsulation and information hiding are about: if the designer of the class makes a variable private, then only the component that owns it can modify or access it.

Of course, the dirty little secret in Java is that reflection can get you around any private restriction.

But you should not resort to that. You should design your classes appropriately and respect the designs of others.

查看更多
登录 后发表回答