Using a non-static variable in a static method JAVA

前端 未结 4 2132
臣服心动
臣服心动 2021-01-17 06:12

So I am writing a very large java code, within this code I want it to output files in a particular file format. In this instance it is going to be a simple .txt file.

4条回答
  •  悲哀的现实
    2021-01-17 06:51

    Without knowing much about your specific requirement, my first thought is that perhaps either your non-static variable or your static method belong somewhere else.

    IMHO, when a class hold variable, non-static contents, it's probably a bad idea to provide static accessor functions that use that variable. I think the best solution is to separate the two, giving the responsibility of storing the mutable data in some Data Provider class that can provide a DEFENSIVE COPY of this variable. Perhaps you don't see the need for it because your example deals with a primitive value. But, if you were to change that to some object reference, you could run into all sorts of problems; one of which is that your code will not be thread-safe.

    public class MyDataProvider {
      private Object nonStaticVariable;
    
      public MyDataProvider () {
        // ...
      }
    
      public Object getNonStaticVariable() {
        Object copy = new Object();
        // copy the internals from nonStaticVariable to copy
        return copy;
      }
    }
    

    Then, your utility class can use the copy of nonStaticVariable to do its work...

    public class MyUtilityClass {
      public static void outputToTxt(Object nonStaticVariableCopy) {
        // do your work
      }
    }
    

    This solution solves all those problems:

    1. Allows a non-static variable to be used by a static method
    2. Your code will be thread-safe because you are using a copy of the non-static variable instead of the original variable.
    3. Separation of concerns: Your utility class doesn't store any variables; thus all methods of the utility class can be static (like Java's Math class), and your Data Provider can be the container that holds your variables.

    Again, in my opinion, this is a much more robust solution.

提交回复
热议问题