Is there a way to access the variables of the call

2019-05-23 00:56发布

问题:

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.

回答1:

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


回答2:

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.



回答3:

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